【问题标题】:How do I pick files with respect to a particular folder in python?如何在 python 中选择与特定文件夹相关的文件?
【发布时间】:2020-05-13 12:37:12
【问题描述】:

我有一个由企业制定的特定文件夹结构,即“/content/2020/May/13-05-2020”。 目前我正在使用该位置的所有文件。

但我更愿意根据每日批处理过程(如文件路径中提到的日期)选择/使用文件。

为简单起见,让我们在文件路径中说,如果今天的日期、5 月和 2020 年存在,那么它应该使用 "/content/2020/May/13-05-2020" 处理文件。

否则,它应该以相同的方式检查年、月和日,并进行相应的处理。

【问题讨论】:

  • 你在哪里遇到了问题?
  • 你能分享更多关于你的问题的细节吗?
  • 您需要提供minimum viable example 以便人们正确评估您的问题。
  • 直接用日期建一个路径,然后调用os.path.exists方法看是否存在。如果是,您可以调用 os.listdir() 方法列出该文件夹中的文件;如果 os.path.exists 方法返回 false,做你想做的其他事情。

标签: python filepath


【解决方案1】:

这可能是您正在寻找的:

from datetime import datetime
import os

today = datetime.today()
date = today.date()
month = today.strftime("%B")
year = today.year

path = os.path.join("/content", str(year), str(month), str(date))
print(path)

【讨论】:

    【解决方案2】:

    也许这有帮助:

    import datetime
    import os
    
    date = datetime.datetime.today().strftime('%Y-%m-%d')
    month = datetime.datetime.today().month
    year = datetime.datetime.today().year
    
    mypath = os.path.join("/content", str(year), str(month), str(date))
    
    if not os.path.exists(mypath):
        print("No folder for the current date found!")
    else:
        os.chdir(mypath)
    

    【讨论】:

    • 这里有几个问题,首先,您没有在mypath 中保留绝对路径,因为您没有在开头放置/。其次,你使用os.chdir 到路径,然后检查它是否存在,什么时候应该是相反的。
    • 感谢您的反馈 :)
    • 感谢大家的支持。
    猜你喜欢
    • 1970-01-01
    • 2022-11-11
    • 1970-01-01
    • 2012-08-14
    • 1970-01-01
    • 2018-02-18
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    相关资源
    最近更新 更多