2014-01-10 116 views
0

我试图搜索目录中任何.csv文件中的第一列是否具有以下值:TPW或KPM1或KPM2Python:在第一列搜索目录中的.csv文件的第一列

如果是的话我想把这个文件名写入文件“Outfile_Files.txt”。

我仍然无法正确搜索;请赐教。

import os 
import string 

outfile = open("Outfile_Files.txt","w") 

for filename in os.listdir("."): 
    if filename.endswith('.csv'): 
     with open(filename, 'r') as f: 
      for line in f: 
       words = line.split(",")         
       if words[0] in "TPW" or "KPM1" or "KPM2": 
        print words[0] 
        outfile.write(filename+ '\n') 
        break; 
outfile.close() 

回答

0

为了测试组成员资格,你应该使用

if words[0] in {"TPW", "KPM1", "KPM2"}: 

if words[0] in "TPW" or "KPM1" or "KPM2": 

条件words[0] in "TPW" or "KPM1" or "KPM2"总是在布尔环境评估为True。第一个Python评估words[0] in "TPW"。如果words[0]"TPW"的子串,那么整个条件是True。 如果单词[0]不是“TPW”的子串,那么Python会跳转到"KPM1",它不是空字符串,并且在布尔上下文中始终为True

相关问题