首页 > 解决方案 > 提取目录中的文件夹名称列表后,如何使用 Python 将它们重命名为另一种格式?

问题描述

我想清理我的文件,并且在提取目录中的文件夹列表后目前卡住了。我想提取文件夹的日期部分并根据这些日期生成 .txt 文件。

下面我使用的代码:

    import os

root ="C:\\Users\\Mr. Slowbro\\Desktop\\Test Python\\"
dirlist = [ item for item in os.listdir(root) if os.path.isdir(os.path.join(root, item)) ]
print (dirlist)

输出如下列表:

['20 年 1 月 1 日 - Alpha'、'9 月 8 日 - Bravo'、'18 年 12 月 31 日 - 收据文件夹']

如何获得以下输出并将它们生成为另一个文件夹中的 .txt 文件?

例如。

20 年 1 月 1 日.txt

19 年 9 月 8 日.txt

12 月 31 日 18.txt

标签: pythondirectoryrename

解决方案


据我了解,我们需要.txt为每个与问题中的名称相称的目录名称创建一个文件。

我们可以拆分每个目录-并构建文件名,例如:

import os
target_dir = "path\\to\\directory\\"
for _dir in dirlist:
    filename = _dir.split("-")[0].strip() + ".txt" # get the date and add extension
    filepath = os.path.join(target_dir, filename)
    with open(filepath, "w") as f: pass # create file

推荐阅读