【问题标题】:Loop over file names in a folder and return file name if a key word is in the file如果文件中有关键字,则循环遍历文件夹中的文件名并返回文件名
【发布时间】: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) 。但是还是不行。

标签: python loops file


【解决方案1】:

您可以通过创建具有密钥的文件列表来尝试这样做:

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)))
    

【讨论】:

  • 很高兴它对您有所帮助,我刚刚使用with 编辑以正确打开文件,请注意这一点。编码快乐!:)
  • open as 和直接赋值有什么区别?实际上,我尝试使用 open as 进行编辑,但它没有按预期显示。第一种方法有效。
  • 基本上“with”允许你不要忘记关闭你已经打开的文件,作为一个打开/关闭封装。查看link1link2 的更多差异。希望它会很清楚。
猜你喜欢
  • 2016-12-18
  • 1970-01-01
  • 2015-12-24
  • 1970-01-01
  • 1970-01-01
  • 2020-09-06
  • 1970-01-01
  • 2014-04-24
  • 1970-01-01
相关资源
最近更新 更多