Python loop through folders and rename files - python

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

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

You need os.walk. It returns a 3-tuple (dirpath, dirnames, filenames) that you can iterate.

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)

Related

Getting paths to all files in a directory (but not absolute path) in Python 3

I have a directory DATA which contains several subdirectories and inside each subdirectory, there are more directories and files.
Here is my code:
for dirpath,subs,filenames in os.walk("/Users/.../DATA"):
for f in filenames:
print(os.path.abspath(os.path.join(dirpath, f)))
The results this code prints out are the absolute directories (ex. "/Users/.../Data/SubFile/SubFile.txt")
The results I want are (ex. "Data/SubFile/Subfile.txt")
What about something simple like this:
dir_path = "/Users/.../DATA"
for dirpath,subs,filenames in os.walk("/Users/.../DATA"):
for f in filenames:
print(os.path.abspath(os.path.join(dirpath, f))[len(dir_path):])
Use os.path.commonprefix():
common_prefix = os.path.commonprefix(["/Users/.../DATA"])
for dirpath, subs, filenames in os.walk("/Users/.../DATA"):
for f in filenames:
print(os.path.relpath(os.path.join(dirpath, f), common_prefix))

How to rename multiple files in a directory using os walk and split in PYTHON?

I need to create a copy of a directory tree called "caritemscopy" where all files, instead of being in directories named after years, rather have the year as part of the filename, and the year directories are entirely absent
My directory currently looks like this
After coding my directory should looks like this
It will list all directory files in path, then rename it and save all files at path and remove the empty directory.
import os
path = 'path_of_folder/F26/'
files = []
# r=root, d=directories, f = files
for r, d, f in os.walk(path):
for file in f:
if '.txt' in file:
files.append(os.path.join(r, file))
for f in files:
src = f.split('/')
os.rename(f, path + src[-2]+'-'+src[-1])
if not os.listdir(path+src[-2]):
os.rmdir(path+src[-2])
else:
pass

How to replace the txt file in a directory

There is directory A, which contains several subdirectories of txt files. There is another directory B, which contains txt files. There are several txt files in A that have the same name in B but different content. Now I want to move the txt files in B to A and cover the files with the same name. My Code is as below:
import shutil
import os
src = '/PATH/TO/B'
dst = '/PATH/TO/A'
file_list = []
for filename in os.walk(dst):
file_list.append(filename)
for root, dirs, files in os.walk(src):
for file in files:
if file in file_list:
##os.remove(dst/file[:-4] + '.txt')
shutil.move(os.path.join(src,file),os.path.join(dst,file))
But when I run this, it did nothing. Can anyone help me about it?
The following will do what you want. You need to be careful to preserve the subdirectory structure so as to avoid FileNotFound exceptions. Test it out in a test directory before clobbering the actual directories you want modified so you know that it does what you want.
import shutil
import os
src = 'B'
dst = 'A'
file_list = []
dst_paths = {}
for root, dirs, files in os.walk(dst):
for file in files:
full_path = os.path.join(root, file)
file_list.append(file)
dst_paths[file] = full_path
print(file_list)
print(dst_paths)
for root, dirs, files in os.walk(src):
for file in files:
if file in file_list:
b_path = os.path.join(root, file)
shutil.move(b_path,dst_paths[file])

Python: Changing filenames and folder names in all folders and subfolders

I want to change the file names and folder names in a given directory and all subfolders. My folder structure is as follows:
top directory
file1
file2
folder1
file1
file2
file3
file4
folder2
file1
file2
file3
file4
I get the following error when executing the code below. I already checked the forums, but couldn't find a solution. Could someone please help me solve this issue and let me know what I need to do to get the program working?
Or is there a better solution for renaming files and folders in a tree?
Error message
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'Filename 1' -> 'filename_1'
Code
#Change file names and folder names in a given directory and all its
subfolders
import os
os.chdir("path\\to\\folder")
print(os.getcwd())
#Walk the directory and change the file names and folder names in all folders and subfolders.
for root, dirs, files in os.walk("path\\to\\folder"):
for dir_name in dirs:
os.rename(dir_name, dir_name.replace(" ", "_").lower())
for file_name in files:
os.rename(file_name, file_name.replace(" ", "_").lower())
#Print done once all files have been renamed.
print("done")
You need to use root otherwise the rename can't find the path:
for root, dirs, files in os.walk("path/to/folder"):
for name in dirs + files:
os.rename(os.path.join(root, name), os.path.join(root, name.replace(" ", "_").lower()))
could it be that you're walking on a folder while renaming it so that it can't be found?
looks like you first need to rename the files and only then the dirs (and even then - make sure it's bottom up)
Try to change the filename first, otherwise you'll change the dir_name and lose reference.
Following solution works most of the time, still issues like same name files may exist after normalizing the name.
import os
os.chdir("path/to/dir")
print(os.getcwd())
#Walk the directory and change the file names and folder names in all folders and subfolders.
for root, dirs, files in os.walk("path/to/dir", topdown=False):
for file_name in files:
new_name = file_name.replace(" ", "_").lower()
if (new_name != file_name):
os.rename(os.path.join(root, file_name), os.path.join(root, new_name))
for dir_name in dirs:
new_name = dir_name.replace(" ", "_").lower()
if (new_name != dir_name):
os.rename(os.path.join(root, dir_name), os.path.join(root, new_name))
Here I copied all files inside of each subfolder to another path.
First use os.listdir() to move through each folder, then use it to move through files which are inside of the folder path. Finally use os.rename() to rename file name. Here, I changed file name to folder name_file name which is "folder_file":
path = 'E:/Data1'
path1 = 'E:/Data2'
for folder in os.listdir(path):
for file in os.listdir(path + '/'+ folder):
src = path + '/' + folder + '/' + file
des = path1 + '/' + folder + '_' +file
os.rename(src, des)

How to read a folder name and output result to a string

I have some code for reading directory names and file names
import os
#define the folder you want to use
myfolder = path/to/directory
#read directories
for dirs in os.walk(myfolder):
for dir in dirs:
print("Directory name = %s" %dir
lets say inside -myfolder- I have a directory called -mysecondfolder-
is it possible to output the filename to a string
something like
for dirs in os.walk(myfolder):
for dir in dirs:
targetfolder="%dir"
You could try like this:
for root, dirs, files in os.walk(myfolder, topdown=False):
targetfolder = dirs

Categories