Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

renaming files in a directory + subdirectories in python

Tags:

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.

like image 297
misterjones Avatar asked Feb 02 '26 22:02

misterjones


1 Answers

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))
like image 187
aganders3 Avatar answered Feb 04 '26 12:02

aganders3