Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing blank spaces from a CSV file without creating a new file

I have blank spaces in a csv sheet that I want to get rid of it.

After searching for hours I realized that this is the code for it:

input = open('file.txt', 'wb')
output = open('new_file.txt', 'wb')
writer = csv.writer(output)
for row in csv.reader(input):
    if any(field.strip() for field in row):
        writer.writerow(row)
input.close()
output.close()  

My question is: How do I remove the blank spaces without having to create a new file?

like image 657
Nick M. Avatar asked Sep 10 '25 07:09

Nick M.


1 Answers

You can first extract the valid rows and overwrite the file afterwards, provided your file is not too big and thus the rows can fit in the memory entirely

with open('file.txt', 'rb') as inp:
    valid_rows = [row for row in csv.reader(inp) if any(field.strip() for field in row)]

with open('file.txt', 'wb') as out:
    csv.writer(out).writerows(valid_rows)
like image 96
Eli Korvigo Avatar answered Sep 12 '25 21:09

Eli Korvigo