小编tge*_*ard的帖子

有没有更好的方法从Python中的文件中读取元素?

我编写了一个粗略的Python程序,用于从CSV文件中的索引中提取短语,并将这些行写入另一个文件.

import csv

total = 0

ifile = open('data.csv', "rb")
reader = csv.reader(ifile)

ofile = open('newdata_write.csv', "wb")
writer = csv.writer(ofile, delimiter='\t', quotechar='"', quoting=csv.QUOTE_ALL)

for row in reader:
    if ("some text") in row[x]:
        total = total + 1
        writer.writerow(row)
    elif ("some more text") in row[x]:
        total = total + 1   
        writer.writerow(row) 
    elif ("even more text I'm looking for") in row[x]:  
        total = total + 1   
        writer.writerow(row)

   < many, many more lines >

print "\nTotal = %d." % total

ifile.close()
Run Code Online (Sandbox Code Playgroud)

我的问题是:是不是有更好的(更优雅/更简洁)Pythonic方式来做到这一点?我觉得这是一个不知道我不知道的情况.我正在搜索的CSV文件不大(3863行,669 KB),所以我认为没有必要使用 …

python csv list

4
推荐指数
1
解决办法
170
查看次数

标签 统计

csv ×1

list ×1

python ×1