我有一个csv文件,其中包含特定列中的字符串和其他值中的其他值。我也有一个字符串列表。 在线上循环,我想检查列表中的一个字符串是否完全包含在csv文件的行中。 如果是,则该行必须写入新的csv文件。Python 2.7匹配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文件的列添加字符串的精确匹配?
“精确”匹配我的意思是:如果CSV有是“string111”它写入新的csv文件,因为“string1”包含在“string111”中,但我不希望如此,我只想在第一个csv中存在“string1”的情况下写入新的csv文件文件。 – giube
csv文件是行喜欢的列表:22/06/2017 04:00:32 | string1 | value1 – giube