Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/320.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中使用csv模块中的字符串进行搜索时遇到问题_Python_Python 2.7_Csv - Fatal编程技术网

在Python中使用csv模块中的字符串进行搜索时遇到问题

在Python中使用csv模块中的字符串进行搜索时遇到问题,python,python-2.7,csv,Python,Python 2.7,Csv,我有一个带有字符串的csv文件partList.csv,我想用它来搜索一组更大的txt文件。由于某种原因,当我使用直接字符串'l99'时,我得到了一个结果。当我从csv加载字符串L99时,我没有得到任何结果 partList.csv仅在第一列中包含带有零件号的单元格,其中一个是L-99txt\u files\u sample\5.txt是一个文本文档,在某些情况下包含字符串L 99 我的代码: def GetPartList(): partList = [] f = open('

我有一个带有字符串的csv文件
partList.csv
,我想用它来搜索一组更大的txt文件。由于某种原因,当我使用直接字符串'l99'时,我得到了一个结果。当我从csv加载字符串L99时,我没有得到任何结果

partList.csv
仅在第一列中包含带有零件号的单元格,其中一个是L-99
txt\u files\u sample\5.txt
是一个文本文档,在某些情况下包含字符串L 99

我的代码:

def GetPartList():
    partList = []
    f = open('partList.csv', 'rb')
    try:
        reader = csv.reader(f)
        for row in reader:
            part = row[0].replace('-',' ').strip()
            partList.append(part)
    finally:
        f.close()
    return partList

def FindFileNames(partList):
    i = 0
    files = []
    for root, dirs, filenames in os.walk('txt_files_sample'):
        for f in filenames:
            document = open(os.path.join(root, f), 'rb')
            for line in document:
                if partList[i] in line:
                #if 'L 99' in line:
                    files.append(f)
                    break
            i = i + 1
    return files

print FindFileNames(GetPartList())
上面的代码生成:

>>> []
如果我取消注释
如果行中的'l99',
并注释掉
如果行中的partList[I:
我得到结果:

>>> ['5.txt']
因此,使用输入,我发现问题在于如何循环使用
零件列表。重写
FindFileNames()
有效:

def FindFileList(partList):
    i = 0
    files = []
    for root, dirs, filenames in os.walk('txt_files'):
        for f in filenames:
            a = 0
            document = open(os.path.join(root, f), 'rb')
            for line in document:
                if a is 1:
                    break
                for partNo in partList:
                    if partNo in line:
                        files.append(f)
                        a = 1
            document.close()
    return files

通过更新代码,我得到了一个精确的文件名列表。

为什么要使用
I
来索引
partList
?您正在针对不同的文件测试
partList
中的每个元素。
partList
在这里包含什么?是的,我自己也在看。我将进行编辑,让我知道您的想法。您不会关闭文件,可能会将搜索分解到自己的函数中,并在一行中找到任何零件号后立即返回,这会更有效。或者甚至是正确的,因为现在包含多个零件号的文件将多次添加到文件列表中。