【发布时间】:2017-06-22 14:15:22
【问题描述】:
我有一个 csv 文件,其中包含特定列中的字符串和其他列中的其他值。我还有一个字符串列表。 循环遍历行,我想检查列表中的字符串之一是否完全包含在 csv 文件的行中。 如果是,则此行必须写入新的 csv 文件。
csv 文件是一个行列表,例如:
22/06/2017 04:00:32 | string1 | value1
22/06/2017 04:00:32 | string11 | value2
22/06/2017 04:00:32 | string2 | value3
22/06/2017 04:00:32 | string3 | value4
我写了这段代码,它工作正常,但它没有考虑字符串的“精确”匹配。
import os, csv
def filter_csv(folderpath):
list1 = [
('name1',1,'string1','value1'),
('name2',2,'string2','value2'),
('name3',3,'string3','value3'),
('name4',4,'string4','value4'),
...
]
def column(matrix, i):
return [row[i] for row in matrix]
col = column(list1,2)
for file in os.listdir("%s" % folderpath):
if file.endswith(".csv"):
new_file = 'new_'+file
filepath = os.path.join("%s" % folderpath, file)
new_filepath = os.path.join("%s" % folderpath, new_file)
with open('%s' % filepath) as csvfile:
lines = csvfile.readlines()
with open('%s' % new_filepath, 'wb') as csvfile2:
for line in lines:
for namevar in col:
if namevar in line:
csvfile2.write(line)
return
如何为 csv 文件的一列添加精确匹配的字符串?
【问题讨论】:
-
"exact" 匹配我的意思是:如果在 csv 中有“string111”,它会写入新的 csv 文件,因为“string1”包含在“string111”中,但我不希望这样,只有当第一个 csv 文件中有“string1”时,我才想写入新的 csv 文件。
-
csv 文件是喜欢的行列表:22/06/2017 04:00:32 |字符串1 |值1
标签: python string python-2.7 match