【问题标题】:Editing bad lines in CSV file编辑 CSV 文件中的坏行
【发布时间】:2020-11-18 18:53:10
【问题描述】:

我有一个 CSV 文件如下:

fruit, country,  city
banana, japan, tokyo
apple, brazil, rio
apple, korea, south, seoul
banana, denmark, copenhagen

这是一个例子,实际上,我在多个大文件中都有这个问题。问题是我无法读取带有逗号分隔符的第 4 行,因为它的一列太多了。

我的想法是

  1. 用 csv.reader 打开文件
  2. 在第 2 列中查找 term1 和在第 3 列中包含 term2 的行(在我的示例中,term1=korea 和 term2=south)
  3. 将第 2 列中的 term1 替换为 term1 和 term2 组合(韩国南部)并删除该行中的第 3 列
  4. 保存编辑后的文件

在下面的代码中,我已经完成了前两个步骤,但我被困在第 3 步和第 4 步。

import csv

path = r'C:\Users\jlobo\Desktop\example.txt'

with open(path, newline='') as csvfile:
    csv_read = csv.reader(csvfile, delimiter=',', quotechar='"') #
    
    for row in csv_read:
        search_terms1 = ["korea"]
        search_terms2 = ["south"]

        if any([term in row[1] for term in search_terms1]) and any([term in row[2] for term in search_terms2]):
            print(row)

如何执行第 3 步和第 4 步?或者如果相关,是否有替代解决方案?

【问题讨论】:

  • 这是我的第一篇文章,欢迎任何关于最佳实践的 cmets
  • 你知道如何编写一个新的 CSV 文件吗(不考虑步骤 2 和 3)?
  • 嗨,为了确定,我想一个简单的搜索和替换 ('korea, south' -> 'korea south') 行不通?
  • 如果有像korea, south 这样的术语,发生的情况是你缺少引号,所以很可能你不应该通过删除逗号来加入它们,而是留下逗号和在 "korea, south" 等两个术语周围添加引号。我看到您还指定了quotechar='"',所以应该可以正常工作。

标签: python csv


【解决方案1】:

首先定义一个列表ARRAY = [],然后在处理行时将它们附加到该数组中

search_terms1 = ["korea"]
search_terms2 = ["south"]

if any([term in row[1] for term in search_terms1]) and any([term in row[2] for term in search_terms2]):
    row[1] =  row[2] + row[1] # combie south and korea
    row.pop(2) # remove the 3rd element

ARRAY.append(row)

然后你可以再次写入文件

with open("new_file.csv", "w") as f:
    for row in ARRAY: # Write each row
        f.write(", ".join(row))
        f.write("\n") # add a new line

我真的不知道csv.reader 是如何工作的,可能有一些功能比这做得更好,但是上面的 sn-p 应该可以正常工作。

【讨论】:

  • 为什么不直接拆分数组?
  • 分割数组是什么意思?你的意思是加入吗?现在我看到f.write(", ".join(row)) 更好了。
猜你喜欢
  • 2017-09-16
  • 2016-04-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-08
相关资源
最近更新 更多