簡體   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