使用csv包从Python中的csv文件中提取特定数据

时间:2019-05-22 14:07:49

标签: python csv

我有14000行,每个csv文件有两个字段,并且正在尝试删除随机出现的一些行。我打算保留除包含以下任何内容的行以外的所有内容:“站名”,“位置代码”,“参数”。

我正在尝试打开包含数据的文件以及将用于将新数据写入其中的新的空csv文件。 我试图遍历csv文件的每一行,并仅将不具有第一个字段等于任何上述值的行写入新文件。

我正在尝试以下操作,但最终得到的是原始数据的精确副本。

import csv
with open('combined_csv.csv', newline='') as inp, open('edited.csv', 'w', newline='') as out:
    writer = csv.writer(out)

    for row in csv.reader(inp):
        if row[0] != "Station Name" and "Location Code" and "Parameter":
            writer.writerow(row)

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

您的if语句无法按预期工作。如果要检查字符串是否与多个字符串不相等,建议您这样做:

if row[0] not in ("Station Name", "Location Code", "Parameter"):
    writer.writerow(row)

更新。

  

您的版本运行良好,但为什么我的版本不起作用?

if row[0] != "Station Name" and "Location Code" and "Parameter":

您正尝试检查row[0]"Station Name" and "Location Code" and "Parameter"不相等。

让我们打印它:

>>>"Station Name" and "Location Code" and "Parameter"
'Parameter'

为什么?让我们做一些实验:

>>>"Station Name" and "Location Code" and "Test"
'Test'

>>>False and "Station Name" and "Location Code" and "Test"
False

>>>"" and "Station Name" and "Location Code" and "Test"
''

>>>"Station Name" and "Location Code" and "" and "Test"
''

还有问题吗?好吧:

>>bool("Non-empty string")
True

>>>bool("")
False

因此,您的代码等同于

if row[0] != "Parameter":

如何正确编写。

if row[0] != "Station Name" and row[0] != "Location Code" and row[0] != "Parameter":
相关问题