Rename images to the folder name with Python - python

I want to rename images that were previously copied from multiple subfolders to the name of the subfolder from which the image came. With my actual code I can only rename images, when I enter the actual file name. But this name always varies.
For example:
C:/sub/folder/1/
rename these images from this folder to 1.jpg
My actual code:
paths = (os.path.join(root, filename)
for root, _, filenames in os.walk(dir_dst):
for filename in filenames:
for path in paths:
newname= path.replace('image_name','new_image_name')
if newname != path:
os.rename(path, newname)
I hope you understand what I mean.

Have you tried something like this
x = os.path.abspath('file_to_rename')
x = os.path.dirname(x)
x = os.path.basename(x)
That will set the name of the current folder to x. From there you could design some incrementing loop with i and rename your files to
os.rename('file_to_rename', x + '_' + str(i))
and then just increase i += 1

I've found the solution:
import os, shutil
src_g = os.getcwd()
dst_g0 = src_g.split('\\')
dst_g0.pop()
dst_g = '\\'.join(dst_g0)+'\\DestinationFolder\\'
for i in os.listdir(src_g):
if os.path.isdir(i):
name = i
neuer_pfad = src_g+'\\'+name+'\\folder_with_images\\'
for j in os.listdir(neuer_pfad):
neue_datei = neuer_pfad+j
if os.path.isfile(neue_datei):
shutil.copyfile(neue_datei, dst_g+name+'_'+j)

Related

Renaming all files in a folder with python using specific condition

I have a folder which has files with names:
"fileX.JPG" where X = 1....N
and I want to name the files as :
"000000000X.JPG" where X=1...N
The new name of the file should have the number from the old name of the file plus the zeros. so example file names I want is:
0000000000001.jpg
0000000000011.jpg
0000000000111.jpg
etc
The file name is 13 characters long. so should have zeros accordingly.
I have not started my code. Don't know where should I start.
You can use os.rename() from the os module
for path in pathlib.Path("a_directory").iterdir():
if path.is_file():
old_name = path.stem
#original filename
old_extension = path.suffix
#original file extension
Also try this:
import os
path = '/Users/myName/Desktop/directory'
files = os.listdir(path)
for index, file in enumerate(files):
os.rename(os.path.join(path, file), os.path.join(path, ''.join([str(index), '.jpg'])))
directory = path.parent
#current file location
new_name = "text" + old_name + old_extension
path.rename(pathlib.Path(directory, new_name))
You can use os.rename.
For example:
for file in os.listdir():
# Get the number, e.g.:
old_number = file.strip("file")[1].strip(".JPG")[0]
os.rename(file, f"{old_number}.JPG")
You might have to adapt based on how your files are actually namd
import os
# Function to rename multiple files
def main():
for count, filename in enumerate(os.listdir("path-to-files")):
d = str(count).zfill(12)
dst = d + ".jpg"
src ='path-to-file'+ filename
dst ='path-to-file'+ dst
# rename() function will
# rename all the files
os.rename(src, dst)
# Driver Code
if __name__ == '__main__':
# Calling main() function
main()

Python - renaming files twice with os

I am currently working on a script to take raw text files, place them in correct year folders based on a version number system, and rename them so that our devs can integrate them into our product easily.
The file in question is called APR30CaseRVU-1Day.txt.
I need this to be in the form refAPRCaseRVU-1Day.txt.
Append ref, remove 30, keep 1Day.
The script works fine for the other files that do not have this extra "1Day". I'm a beginner so I'm sure my workflow is shit but my idea was to use os.rename twice. Once to remove the characters, and then split on the hyphen to add the "1" back in to the filename, but when I print the filename after the first os.rename it still has 30 and 1.
Anyone have any tips to do this more effectively?
folder = r"C:\Users\xx\Desktop\Python Final Project\Raw"
import os
import re
import shutil
for root, dirs, filenames in os.walk(folder):
for filename in filenames:
srcpath = os.path.join(root, filename)
#split the filename so that we can rename accordingly below, filename_split[0] = filename, filename_split[1] = file ext
filename_split = os.path.splitext(filename)
name = filename_split[0]
ext = filename_split[1]
newfolder = ''
destpath = os.path.join(newfolder, "ref" + re.sub(r'\d', '', filename_split[0]) + filename_split[1])
#first step: remove AP files entirely from directory
if filename.startswith("AP27"):
os.remove(os.path.join(folder, filename))
#the rest include a version number that must be routed to the correct year folder directory created above
elif filename.__contains__("30") and filename.__contains__("Day"):
newfolder = r"C:\Users\xx\Desktop\Python Final Project\Raw\2013"
os.rename(os.path.join(root, filename),
os.path.join(newfolder, "ref" + re.sub(r'\d', '', filename_split[0]) + filename_split[1]))
print(filename)
day_name = re.split(r'[\s-]+', filename)
print(day_name)
first_name = day_name[0]
last_name = day_name[1]
os.rename(os.path.join(newfolder, filename),
os.path.join(newfolder, "ref" + first_name + '1' + last_name))
I solved this myself:
os.rename(os.path.join(root, filename),
os.path.join(newfolder, "ref" + re.sub(r'\d{2}', '', name) + ext))
Adding the {2} made it look for 2 consecutive numbers, and left the 1 alone.
Thanks!

Python - Renaming all files in a directory using a loop

I have a folder with images that are currently named with timestamps. I want to rename all the images in the directory so they are named 'captured(x).jpg' where x is the image number in the directory.
I have been trying to implement different suggestions as advised on this website and other with no luck. Here is my code:
path = '/home/pi/images/'
i = 0
for filename in os.listdir(path):
os.rename(filename, 'captured'+str(i)+'.jpg'
i = i +1
I keep getting an error saying "No such file or directory" for the os.rename line.
The results returned from os.listdir() does not include the path.
path = '/home/pi/images/'
i = 0
for filename in os.listdir(path):
os.rename(os.path.join(path,filename), os.path.join(path,'captured'+str(i)+'.jpg'))
i = i +1
The method rename() takes absolute paths, You are giving it only the file names thus it can't locate the files.
Add the folder's directory in front of the filename to get the absolute path
path = 'G:/ftest'
i = 0
for filename in os.listdir(path):
os.rename(path+'/'+filename, path+'/captured'+str(i)+'.jpg')
i = i +1
Two suggestions:
Use glob. This gives you more fine grained control over filenames and dirs to iterate over.
Use enumerate instead of manual counting the iterations
Example:
import glob
import os
path = '/home/pi/images/'
for i, filename in enumerate(glob.glob(path + '*.jpg')):
os.rename(filename, os.path.join(path, 'captured' + str(i) + '.jpg'))
This will work
import glob2
import os
def rename(f_path, new_name):
filelist = glob2.glob(f_path + "*.ma")
count = 0
for file in filelist:
print("File Count : ", count)
filename = os.path.split(file)
print(filename)
new_filename = f_path + new_name + str(count + 1) + ".ma"
os.rename(f_path+filename[1], new_filename)
print(new_filename)
count = count + 1
the function takes two arguments your filepath to rename the file and your new name to the file

Create a duplicate of a folder and the folders in it, while changing their names

I'm trying to create an output folder/file for a batch script I'm running on every file in a folder. I would like it if when I found all the files or folders in the targetFolder I could create a targetFolder_output, and if targetFolder has a folder, anotherFolder, in it I could create anotherFolder_output in targetFolder_out.
So in the end I have C:\targetFolder\anotherFolder and it's duplicate C:\targetFolder_output\anotherFolder_output
I plan to do this with all of the files in there, but I think if I can get over this folder hurdle, I can handle the file one.
import os
targetFolder = "C:\\Users\\MyUserName\\Desktop\\tests"
outputFolder = targetFolder + "_output"
# Iterate over everything in the targetFolder
for directory, subdirectories, files in os.walk(targetFolder):
folderBasename = (os.path.basename(directory) )
if not os.path.exists(outputFolder + "\\" + folderBasename + "_output"):
os.makedirs(outputFolder + "\\" + folderBasename + "_output")
So far all this is doing is making a folder on my desktop "tests_output" with the folders:
tests_output\tests_output
tests_output\level2_output
tests_output\level3_output
What I would like to see is:
tests_output\level2_output\level3_output
Any help will be very much appreciated!
import os
class FCopy(object):
def __init__(self, source):
self.source = source
self.target = os.path.join(source, '_output')
if not os.path.exists(self.target):
os.makedirs(os.path.abspath(self.target))
self.lf, self.ld = [], []
def walk(self, path):
for x in (os.path.join(path, x) for x in os.listdir(path)):
if x == self.target:continue
if os.path.isfile(x):
self.lf.append(x)
elif os.path.isdir(x):
self.ld.append(x)
self.walk(x)
#extra code if you want to handle symlinks
def do(self):
#if thats all you want,
#code this directly in walk
self.walk(self.source)
for x in self.ld:
x = x.replace(self.source, self.target)
os.makedirs(x)
for x in self.lf:
x = x.replace(self.source, self.target)
with open(x, 'w') as f:pass
f = FCopy('C:\\PerfLogs\\w\\tmp\\codemirror')
f.do()
You may play with ifexists and so on.
If all you want is double the structure of source, then you could move the creation of files/dirs in walk, in corresponding if...else
P.S.: ignore my dir, I just make a test in it

A possible loop to rename files in order from a directory?

I have a 100 .fits files in a directory with long names (ex. spec-0355-51788-0484.fits spec-0493-51957-0157.fits, spec-0367-51997-0430.fits, spec-0771-52370-0017.fits etc...)
I am wondering if there is a loop to rename them all in a sequence of integers so that it looks like 1.fits, 2.fits, 3.fits, 4.fits, .... 100.fits
You could try this:
import os
import glob
os.chdir("E:/")
i = 1
for old_file in glob.glob("*.fits"):
new = str(i) + ".fits"
os.renames(old_file, new)
i=i+1
I would recommend trying this.
This will rename the files by adding an index before the name of the file.
Example:
How to install.fits, Hello world tutorial.fits, .......
would rename to
1 How to install.fits, 2 Hello world tutorial.fits, ......
import os
path = 'C:/Users/username/Desktop/My files' #path of folder containing files you want to rename
i = 1
for filename in os.listdir(path):
os.rename(os.path.join(path,filename), os.path.join(path, str(i)+ " " + filename + '.fits'))
i = i + 1
If you don't like to put the original file name at all then simply remove adding filename in os.path.join
os.path.join(path, str(i)+ " " + '.fits')) #for not including original file name

Categories