【问题标题】:Skip every particular 2 rows in whole csv file using python使用python跳过整个csv文件中的每2行
【发布时间】:2020-08-25 19:32:03
【问题描述】:

我有一个包含一些数据的 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 文件中存在的某些行有什么办法吗? 感谢您的帮助

【问题讨论】:

标签: python-3.x excel csv web-scraping


【解决方案1】:

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

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

然后您可以查看 dicts 中的特定元素,以及您不喜欢的脚本元素。根据您的示例,如果您尝试删除像 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 文件,然后根据该格式调整我的代码以进行过滤。

【讨论】:

  • 这不是完整的解决方案,即不回答基于出现或正则表达式跳过 csv 行的问题。如果您可以编辑答案以添加该信息,那就太好了。
猜你喜欢
  • 2013-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多