简体   繁体   English

遍历文件夹中的文件名,如果文件中有关键字则返回文件名

[英]Loop over file names in a folder and return file name if a key word is in the file

I'm coding for this simple requirements: Search for a key word and return the file name that has such key word我正在为这个简单的要求进行编码:搜索关键字并返回具有该关键字的文件名

This is the first part of the code to search for 'txt' files.这是搜索“txt”文件的代码的第一部分。 But I'm having problem with looping over file names: code just shows 1 result (file) while it is expected to list all file names.但是我在循环文件名时遇到问题:代码只显示 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: ')))

You could try with this, by creating a list of files that have the key:您可以通过创建具有密钥的文件列表来尝试这样做:

def search_txt(path, keyWord):
    lsfiles=[]
    for file in list_file_name(path):
        if file.endswith('txt'):
            with open(path + '/' + file, 'r') as f:
                openFile = f.read()
                if keyWord in openFile:
                    lsfiles.append(file)
    if len(lsfiles)==0:
        return('No key word found ')
    else:
        return('Key word {} is in {}'.format(keyWord, ', '.join(lsfiles)))
    

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM