繁体   English   中英

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

[英]After extracting the list of folder names in a directory, how do I rename them in another format using 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)

output 列表如下:

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

如何获取以下 output 并在另一个文件夹中生成 as.txt 文件?

例如。

20 年 1 月 1 日.txt

19 年 9 月 8 日.txt

12 月 31 日 18.txt

据我了解,我们需要为每个与问题中的名称相称的目录名称创建一个.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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM