Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rename subfolders in a directory - python

I want to rename all subfolders within a directory using python. I thought this was fairly easy but since i'm new to python and programming in general i'm assuming i'm missing something key.

Here is my folder structure: C:\Users\DBailey\Desktop\Here

-there are two folders with this folder named: 3303_InfigenSolar and 3304_FurnaceCanyon

-within these folders are 4 other subfolders and within those folders are a bunch of files.

I want to batch rename only 3303_InfigenSolar and 3304_FurnaceCanyon so that they read 3303_InfigenSolar_08315 and 3304_FurnaceCanyon_08315

Here is my code thus far:

now = datetime.datetime.now()
month = "0" + str(now.month)
day = now.day
year1 = str(now.year)
year2 = year1[2:]
date = str(month) + str(day) + str(year2)
newname = fn + "_" + str(date)

dir = 'C:\Users\DBailey\Desktop\Here'
folder = os.listdir(dir)
for fn in folder:
    print newname
    os.rename(fn, newname)

When I run the script - only one folder is printed (there are only two folders but more will be added)and I get the following error:

Traceback (most recent call last):
  File "<interactive input>", line 2, in <module>
WindowsError: [Error 2] The system cannot find the file specified
like image 509
David Bailey Avatar asked Sep 28 '22 03:09

David Bailey


2 Answers

You need to os.path.join:

_dir = 'C:\Users\DBailey\Desktop\Here'
os.rename(os.path.join(_dir, fn), os.path.join(_dir,newname))

python is looking in your cwd for fn, you need to use join to tell python where the file is actually located unless you cwd is actually the directory that the file is located.

If you have multiple directories to rename you need to also make sure you create a unique name for each in the loop.

dte = str(date)
for ind,fn in enumerate(folder,1):
    os.rename(os.path.join(_dir, fn), os.path.join(_dir,"{}_{}".format(dte,ind)))

You can use whatever you want to differentiate the folder names, just make sure they are unique. This also presumes you only have directories, if you have files then you need to check that each fn is actually a directory:

dte = str(date)
folder = (d for d in  os.listdir(_dir))
for ind,fn in enumerate(folder,1):
    p1 = os.path.join(_dir, fn)
    if os.path.isdir(p1):
        os.rename(p1, os.path.join(_dir,"{}_{}".format(dte,ind)))
like image 59
Padraic Cunningham Avatar answered Oct 03 '22 07:10

Padraic Cunningham


Also looks like 'fn' is not initialized before referenced in newname. You probably don't need newname really, just do what Padraic said, minus newname:

os.rename(os.path.join(dir,fn), os.path.join(dir, fn + "_" + str(date)))
like image 22
Maelstrom Avatar answered Oct 03 '22 06:10

Maelstrom