Python 3.x 使用python跳过整个csv文件中的每2行
我有一个包含一些数据的csv文件 下面是csv文件的示例Python 3.x 使用python跳过整个csv文件中的每2行,python-3.x,excel,csv,web-scraping,Python 3.x,Excel,Csv,Web Scraping,我有一个包含一些数据的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
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文件中的一些行,有什么办法吗?
感谢帮助< /p> < p>阅读Python中的CSV,只需输入一本包含下列词条的词典,请考虑以下内容:
import csv
with open('mycsv.csv', mode='r') as file:
mycsv = csv.DictReader(file)
然后,您可以查看dicts中的特定元素,为您不喜欢的元素编写脚本。根据您的示例,如果您试图删除这样一行,文件使用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中的备用行吗?是的!如果这些有效,你看过这个吗?这会给出列表中的每一行,因此如何跳过csv中不需要的列表?如果是每隔一行,则可以在循环计数器上使用模运算。你看了我发布的第一个链接了吗?这不是完整的解决方案,也就是说,没有回答基于事件或正则表达式跳过csv行的问题。如果你能编辑你的答案来添加这些信息那就太好了。