【问题标题】:Issue with getting files of certain text in python在 python 中获取某些文本的文件的问题
【发布时间】:2020-10-24 04:36:07
【问题描述】:

我想检查列表req_text 中的每个子字符串是否包含在列表all_files 中的任何文件中。仅当列表req_text 中的每个子字符串都包含在列表all_files 中的至少一个文件中时,程序才应返回True。如果列表all_files 中的任何文件中都不存在一个子字符串,那么它应该返回 False。

all_files = ['amc_20200304.txt', 'hello.py', 'pmc_20190807.txt', 'pmc_20200304.txt', 'pmc_20304.txt']
req_text = ['pmc_20304', 'amc_20200304']

def file_check():    
    all_files = os.listdir(dir)
    print(all_files)
    for f in all_files:     
        for r in req_txt:    
            if r in f:
                print("file exists: " + f)               
                return True
            else:
                print("file not exists: " + f)
                return False

def printt():
    result = file_check()
    print(result)
printt()

当前结果:据说 amc_20200304.txt 不存在但它存在,因为文件在列表中all_files

file not exists: amc_20200304.txt
False

预期:它应该返回 true,因为列表 req_text 中的两个子字符串都包含在列表 all_files 中的文件中。如果列表 all_files 中的任何文件中缺少任何子字符串,则它应该返回 False

【问题讨论】:

    标签: python python-3.x file for-loop


    【解决方案1】:

    很少出错。

    1. all_files 作为all_files = os.listdir(dir) 的一部分被覆盖
    2. 当在amc_20200304.txtpmc_20304 之间进行第一次比较时,else 部分中的 return 语句将返回

    下面是你想要的。

    all_files = ['amc_20200304.txt', 'hello.py', 'pmc_20190807.txt', 'pmc_20200304.txt', 'pmc_20304.txt']
    req_text = ['pmc_20304', 'amc_20200304']
    
    def file_check():    
        print(all_files)
        for r in req_text:
            found = False
            for f in all_files:    
                if r in f:
                    print("file exists: " + f)               
                    found = True
                    break
            if not found:
                print("pattern not exists: " + r)
                return False
        return True
    
    def printt():
        result = file_check()
        print(result)
    printt()
    

    输出

    file exists: pmc_20304.txt
    file exists: amc_20200304.txt
    True
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-06
      • 1970-01-01
      • 2010-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-19
      • 2020-11-03
      相关资源
      最近更新 更多