misterjones
misterjones

Reputation: 41

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.

i.e. 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.

Upvotes: 3

Views: 3710

Answers (3)

Vijayakumar K
Vijayakumar K

Reputation: 11

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

Upvotes: 1

misterjones
misterjones

Reputation: 41

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('.')]

Upvotes: 1

aganders3
aganders3

Reputation: 5945

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))

Upvotes: 7

Related Questions