【问题标题】:Removing blank spaces from a CSV file without creating a new file从 CSV 文件中删除空格而不创建新文件
【发布时间】:2016-06-27 19:20:22
【问题描述】:

我想删除 csv 表中的空格。

搜索了几个小时后,我意识到这是它的代码:

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

我的问题是:如何在不创建新文件的情况下删除空格?

【问题讨论】:

    标签: python python-2.7 csv


    【解决方案1】:

    您可以先提取有效行,然后再覆盖文件,前提是您的文件不太大,因此行可以完全放入内存中

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-04
      • 2015-04-11
      • 2013-01-30
      • 2018-08-15
      • 2012-06-29
      • 2015-03-12
      • 2020-05-21
      相关资源
      最近更新 更多