从CSV文件中删除空格,而不创建新文件 [英] Removing blank spaces from a CSV file without creating a new file

查看:1553
本文介绍了从CSV文件中删除空格,而不创建新文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在csv工作表中有空格,我想摆脱它。

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()  

我的问题是:

推荐答案

您可以先提取有效行,然后覆盖该文件,

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)

这篇关于从CSV文件中删除空格,而不创建新文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆