【发布时间】:2021-04-01 13:27:52
【问题描述】:
我是 python 新手,手头有一个任务。我在一个文件夹中有多个 csv 文件,需要在这些文件中找到一个特定的单词。然后我需要文件名。有没有python的程序员可以给我一些指导?
【问题讨论】:
-
您能否向我们展示您到目前为止所做的尝试?
我是 python 新手,手头有一个任务。我在一个文件夹中有多个 csv 文件,需要在这些文件中找到一个特定的单词。然后我需要文件名。有没有python的程序员可以给我一些指导?
【问题讨论】:
也许是这样的:
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))
【讨论】:
text 时从循环内返回 filename。