0

我有一个 csv 文件,其中包含下面的 csv 文件的一些数据示例

these file is crypted with "asdfg"
Name,Status,Time
abc,failed,7:30

these file is crypted with "asdfgghklm"
Name,Status,Time
def,running,12:30

输出 -

Name,Status,Time
abc,failed,7:30
def,running,12:30

我想使用python跳过整个csv文件中存在的一些行有什么办法吗?谢谢您的帮助

4

1 回答 1

-1

在 python 中读取 csv 只是在包含以下行的字典中考虑以下内容:

import csv
with open('mycsv.csv', mode='r') as file:
    mycsv = csv.DictReader(file)

然后你可以查看字典中的特定元素,你不喜欢的脚本。根据你的例子,如果你想摆脱一条线,就像 these file is crypted with "asdfgghklm"你可以检查是否有第二个元素,如果没有转储它,或者你可以在循环时忽略它

如果您的文件结构与上面提到的完全一样,那么字典应该看起来像这样

OrderedDict([('these file is crypted with "asdfg"', 'Name'), (None, ['Status', 'Time'])])        
OrderedDict([('these file is crypted with "asdfg"', 'abc'), (None, ['failed', '7:30'])])
OrderedDict([('these file is crypted with "asdfg"', 'these file is crypted with "asdfgghklm"')]) 
OrderedDict([('these file is crypted with "asdfg"', 'Name'), (None, ['Status', 'Time'])])        
OrderedDict([('these file is crypted with "asdfg"', 'def'), (None, ['running', '12:30'])])

这是基于代码:

import csv
with open('file.csv', mode='r') as file:
    mycsv = csv.DictReader(file)
    for line in mycsv :
        print(line)

从这里我们可以查看输出并使用 if 语句终止您不想要的内容并打印您想要的内容。您需要根据实际输出进行调整,我喜欢首先使用打印命令来保证我知道系统将如何查看我的 csv 文件,然后根据该格式调整我的代码以进行过滤。

于 2020-08-25T19:54:36.667 回答