【问题标题】:Python: Search for a set of words in first column on .csv files in a directoryPython:在目录中的 .csv 文件的第一列中搜索一组单词
【发布时间】:2014-01-10 11:22:56
【问题描述】:

我正在尝试搜索目录中任何 .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()

【问题讨论】:

    标签: python string csv comparison


    【解决方案1】:

    要测试您应该使用的集合成员身份

    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。 如果 words[0] 不是 "TPW" 的子字符串,则 Python 转到 "KPM1",它不是空字符串,在布尔上下文中始终为 True

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-22
      • 1970-01-01
      • 1970-01-01
      • 2015-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多