【问题标题】:Python file path based on dates基于日期的 Python 文件路径
【发布时间】:2016-09-14 18:55:51
【问题描述】:

创建一个脚本,该脚本将自动处理当天的文件路径,执行一些操作,然后保存到同一目录。

文件夹结构基于日期:

maindir -> year -> month -> 该月的文件。

到目前为止,我的方法是:

year = time.strftime("%Y")
month = time.strftime("%B")
dir = parse('C:\maindir' + '\' + str(year) + '\' + str(month))
os.chdir(dir)

但是,我想稍后将其与os.makedirs 一起使用,以便在我进行时自动生成文件夹结构。

或者创建一个解析目录路径的方法会更好,这样我就可以调用它:

if not os.path.exists(method):
    try:
        os.makedirs(os.path.dirname(method))

更新:

偶然发现这个讨论很有帮助 - constructing absolute path with os.join()

netdrive="\\network.com\mainfolder$"
year = time.strftime("%Y")
month = time.strftime("%B")
path=path.abspath(path.join(os.sep,netdrive,year,month))
if not os.path.exists(path):
    os.makedirs(path)
os.chdir(path)

因此,我在这方面取得了一些进展 - 但是,现在我遇到了识别网络驱动器的问题,因为目前它使用 C:/ 默认值作为 path.abspath 的一部分。我如何将其覆盖到一个新的根驱动器上,而与驱动器映射到什么无关? D:/ 用于一位用户,E:/ 用于第二位 - 等等。

【问题讨论】:

    标签: python windows


    【解决方案1】:

    由于路径仅包含年和月,因此目录平均连续 30 天保持不变。

    因此,最好在创建目录之前检查目录是否已经存在。

    if not os.path.exists(directory):
       os.makedirs(directory)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-05
      • 1970-01-01
      • 2016-06-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-11
      • 1970-01-01
      相关资源
      最近更新 更多