Reputation: 207
I am trying to go through a bunch of folders and go into each one and rename specific files to different names. I got stuck on just the loop through folders part.
My file system looks as follows:
Root Directory
Folder
File1
File2
File3
Folder
File1
File2
File3
The code I have is:
os.chdir(rootDir)
for folder in os.listdir():
print(folder)
os.chdir(rootDir + 'folder')
for f in os.listdir():
print(f)
os.chdir(rootDir)
So in my mind it will go through the folders then enter the folder and list the files inside then go back to the root directory
Upvotes: 2
Views: 10242
Reputation: 21
I know it's been a while, but be aware of the extension as well while using os.rename() after os.walk().
If someone wishes to keep the same extension, then following should work:
import os
path_dir = "/dir/path"
# get all file names in the directory
for dir, subdirs, files in os.walk(path_dir):
for f in files:
# separating the file name and extension
file_name = f.split('.')[0]
ext = f.split('.')[-1]
# new file name
new_file_name = file_name + "<extended_part_of_the_name>" + "." + ext
os.rename(os.path.join(path_dir, f), os.path.join(path_dir, new_file_name))
Upvotes: 1
Reputation: 113950
def change_files(root_dir,target_files,rename_fn):
for fname in os.listdir(root_path):
path = os.path.join(root_path,fname)
if fname in target_files:
new_name = rename_fn(fname)
os.move(path,os.path.join(root_path,new_name)
def rename_file(old_name):
return old_name.replace("txt","log")
change_files("/home/target/dir",["File1.txt","File2.txt"],rename_file)
Upvotes: 0
Reputation: 11322
Have a look at os.walk
import os
for dir, subdirs, files in os.walk("."):
for f in files:
f_new = f + 'bak'
os.rename(os.path.join(root, f), os.path.join(root, f_new))
Upvotes: 4
Reputation: 2562
You need os.walk
. It returns a 3-tuple (dirpath, dirnames, filenames) that you can iterate.
Upvotes: 3