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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With