【问题标题】:Check if a particular file is present in the folder using python使用python检查文件夹中是否存在特定文件
【发布时间】:2021-07-09 10:58:34
【问题描述】:

我想检查某个文件是否存在于特定文件夹中并打印输出。我在路径中有以下文件:./programs/data/my_files:

data.txt
an_123.txt
info.log
an_234.txt
filename.txt
main.py
an_55.txt

我想检查文件data.txt, filename.txt, and an_55.txt是否存在于路径./programs/data/my_files中。输出应该如下:

Success: data.txt exists 

到目前为止我尝试了什么?

pth = str("./programs/data/my_files/")
filename = ['data.txt', 'filename.txt', 'an_55.txt']

for i in filename:
    if glob.glob(os.path.join(pth)):
       print('Success: ', "NaN_"+i+".xml exists")
    else:
       print('Failure: ', "NaN_"+i+".xml does not exists")

这仅对列表中的最后一项(即 an_55.txt)打印成功,其他项为失败。我该如何纠正这个问题?

【问题讨论】:

    标签: python file directory path glob


    【解决方案1】:

    试试这个

    import os
    files = os.listdir("your/path/to/files")
    for file in files:
          if file.startswith("data") # you can also check if the item is a file here os.isfile()
                print("success")
    

    你也可以使用 os.path.exists("path to a file")

    【讨论】:

      【解决方案2】:

      这可能会有所帮助

      from pathlib import Path
      
      my_file = Path("/path/to/file") #add your path lists 
      
      if my_file.is_file():
            print("present")
      else:
            print("not present")
      

      【讨论】:

        猜你喜欢
        • 2019-03-26
        • 1970-01-01
        • 1970-01-01
        • 2018-11-17
        • 2012-02-05
        • 2017-05-14
        • 1970-01-01
        相关资源
        最近更新 更多