【问题标题】:How to search files from a list?如何从列表中搜索文件?
【发布时间】:2020-04-25 13:47:48
【问题描述】:

我有一个清单

fileslist=[1.jpg,2.xml,3.png]

我想在当前工作目录的列表中搜索文件 我试过了

listingdir=os.getcwd()
for rootpath,directories,files in os.walk(listingdir):
    for file in fileslist:
        if file in files:
            print("file:{} found".format(file))

我也试过了

list=(set(files).intersection(fileslist))

但由于文件中不仅有一种类型的扩展而没有工作 当我使用 set 时,它会创建一个如下列表,但我没有得到结果

f=set(files)
print(f)
#result is
[[1.jpg,2.jpg,....],[1.png,2.png,...],[1.xml,2.xml,.......]]

【问题讨论】:

  • 请出示您的真实数据。您的最后一个 sn-p 代码不可能像这样打印结果。
  • 继续阅读os.path.exists(path)

标签: python python-3.x file


【解决方案1】:

如果你只想搜索当前目录,你可以这样做:

files = [f for f in os.listdir() if os.path.isfile(f)]

fileslist = ['1.jpg','2.xml','3.png']
list = (set(files).intersection(fileslist))

输出:

{'1.png'}  # it wont always be this, just an example.

【讨论】:

  • os.listdir(...) path 参数不是必需的,如果您要列出当前工作目录中的文件。所以你可以只使用os.listdir() 而不是os.listdir('.')
  • 没错。它将考虑路径 ('.') 的默认值
【解决方案2】:

您可以使用os.path.isfile(...)。它将检查某个文件是否存在。它可能只接受完整路径或文件名(然后它将检查文件是否存在于当前工作目录中)。

import os.path
fileslist=['1.jpg','2.xml','3.png'] # no, it won't work without the quotes! 
for f in fileslist:
    if os.path.isfile(f):
         print("file:{} found".format(f))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多