简体   繁体   中英

After extracting the list of folder names in a directory, how do I rename them in another format using Python?

I want to cleanup my files and am currently stuck after extracting the list of folders in a directory. I want to extract the date portion of the folders and generate.txt files based on these dates.

Below code I used:

    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)

The output is as below list:

['01 Jan 20 - Alpha', '08 Sept 19 - Bravo', '31 Dec 18 - Receipt Folder']

How do I get the following output and generate them as.txt files in another folder?

eg.

01 Jan 20.txt

08 Sept 19.txt

31 Dec 18.txt

From what I understand, we are required to create a .txt file for every directory name commensurate with the name in the question.

We can split every directory on - and build the filename like:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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