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

2024-04-19 18:09:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个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)

感谢您的帮助


Tags: and文件csv数据代码名称内容站点
1条回答
网友
1楼 · 发布于 2024-04-19 18:09:05

你的if语句不会像你预期的那样起作用。如果要检查字符串是否与多个字符串不相等,我建议您这样做:

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

升级。

Your version works well but why is mine not working?

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":

相关问题 更多 >