2014-01-10 67 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

相關問題