【发布时间】:2020-06-21 04:23:39
【问题描述】:
我正在为这个简单的要求进行编码:搜索关键字并返回具有该关键字的文件名
这是搜索“txt”文件的代码的第一部分。但是我在循环文件名时遇到问题:代码只显示 1 个结果(文件),而它应该列出所有文件名。
import os
#list file names
def list_file_name(path):
fileList = os.listdir(path)
return(fileList)
#Function 1: search key_word in txt file
def search_txt(path, keyWord):
for file in list_file_name(path):
if file.endswith('txt'):
f = open(path + '/' + file, 'r')
openFile = f.read()
if keyWord in openFile:
return('Key word {} is in {}'.format(keyWord, file))
else:
return('No key word found')
continue
#run the function
print(search_txt(input('Please input folder path: '), input('Please input key word: ')))
【问题讨论】:
-
遍历目录stackoverflow.com/questions/10377998/…中的文件;也不要返回巨大的列表,而是将它们作为生成器返回;
-
一个函数只能返回一次。
-
您的意思是:for file in list_file_name(path) 吗?实际上,我尝试删除该功能并直接添加: for file in os.listdir(path) 。但是还是不行。