简体   繁体   中英

renaming files in a directory + subdirectories in python

I have some files that I'm working with in a python script. The latest requirement is that I go into a directory that the files will be placed in and rename all files by adding a datestamp and project name to the beginning of the filename while keeping the original name.

ie foo.txt becomes 2011-12-28_projectname_foo.txt

Building the new tag was easy enough, it's just the renaming process that's tripping me up.

Can you post what you have tried?

I think you should just need to use os.walk with os.rename .

Something like this:

import os
from os.path import join

for root, dirs, files in os.walk('path/to/dir'):
    for name in files:
        newname = foo + name
        os.rename(join(root,name),join(root,newname))

I know this is an older post of mine, but seeing as how it's been viewed quite a few times I figure I'll post what I did to resolve this.

import os

sv_name="(whatever it's named)"
today=datetime.date.today()
survey=sv_name.replace(" ","_")
date=str(today).replace(" ","_")
namedate=survey+str(date)

[os.rename(f,str(namedate+"_"+f)) for f in os.listdir('.') if not f.startswith('.')]
import os

dir_name = os.path.realpath('ur directory')

cnt=0  for root, dirs, files in os.walk(dir_name, topdown=False):
    for file in files:
        cnt=cnt+1
        file_name = os.path.splitext(file)[0]#file name no ext
        extension = os.path.splitext(file)[1]
        dir_name = os.path.basename(root)
        try: 
            os.rename(root+"/"+file,root+"/"+dir_name+extension)
        except FileExistsError: 
            os.rename(root+"/"+file,root+""+dir_name+str(cnt)+extension)

to care if more files are there in single folder and if we need to give incremental value for the files

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