在多个 csv 文件中搜索特定单词

时间:2020-12-22 20:39:31

标签: python string csv search

我是 Python 新手,手头有一项任务。我在一个文件夹中有多个 csv 文件,需要在这些文件中找到一个特定的词。然后我需要文件名。任何 Python 编码人员可以给我一些指导吗?

1 个答案:

答案 0 :(得分:2)

也许是这样的:

from glob import glob
text = 'test'
for filename in glob('*.csv'):
    with open(filename) as input_file:
        if text in input_file.read():
            print(f'{text} was found in file {filename}')

编辑:将其移动到函数中 ->

from glob import glob


def find_files_with_text(pathname, value):
    files_containing_value = []
    for filename in glob(pathname):
        with open(filename) as input_file:
            if value in input_file.read():
                files_containing_value.append(filename)
    return files_containing_value


path = './*.txt'
text = 'test'

print(find_files_with_text(path, text))