[英]Python: Search for a set of words in first column on .csv files in a directory
我正在嘗試搜索目錄中任何.csv文件中的第一列是否具有以下值:TPW或KPM1或KPM2
如果是這樣,那么我想將此文件名寫入文件“ 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()
要測試集合成員身份,您應該使用
if words[0] in {"TPW", "KPM1", "KPM2"}:
不
if words[0] in "TPW" or "KPM1" or "KPM2":
在布爾上下文中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
。 如果words [0]不是“ TPW”的子字符串,則Python轉到"KPM1"
,它不是空字符串,並且在布爾上下文中始終為True
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.