I have a folder named "animals"
Inside the folder I have the following files:
"cat.PNG", "dog.PNG", "horse.PNG", "sheep.PNG"
I know the following code will change the files to lowercase
files = os.listdir('.')
for f in files:
new = f.lower()
os.rename(f, new)
But how would I change this if I wanted the file type to be lower and the name of the animal to be upper of every file?
The cleanest way (which works for any directory and any extension too):
for f in os.listdir(source_dir):
name,ext = os.path.splitext()
os.rename(os.path.join(source_dir,f), os.path.join(source_dir,name+ext.lower())
split name into radix+extension
convert extension to lowercase
perform rename with full path
A really simple solution would be the following:
for f in files:
new = f.upper()
new.replace(".PNG", ".png")
os.rename(f, new)
You can split the file name, do each operation individually, then rejoin them.
files = os.listdir('.')
for f in files:
# Split the filename by '.'
split_filename = f.split('.')
filename = ".".join(split_filename[:-1])
extension = split_filename[:-1]
# Do each operation
filename = filename.upper()
extension = extension.lower()
# Rejoin the filename
new_filename = filename + '.' + extension
# Rename the file
os.rename(new_filename, new)
(base, ext) = f.split('.')
new_name = f'{c.upper()}.{d.lower()}'
os.rename(f, new_name)
You can use split and join, see this example:
file_names = ["cat.PNG", "dog.PNG", "horse.PNG", "sheep.PNG"]
for file_name in file_names:
name, extension = file_name.split('.')
print('.'.join([name.upper(), extension.lower()]))
Related
I need to change file names inside a folder
My file names are
BX-002-001.pdf
DX-001-002.pdf
GH-004-004.pdf
HJ-003-007.pdf
I need to add an additional zero after '-' at the end, like this
BX-002-0001.pdf
DX-001-0002.pdf
GH-004-0004.pdf
HJ-003-0007.pdf
I tried this
all_files = glob.glob("*.pdf")
for i in all_files:
fname = os.path.splitext(os.path.basename(i))[0]
fname = fname.replace("-00","-000")
My code is not working, can anyone help?
fname = fname.replace("-00","-000") only changes the variable fname in your program. It does not change the filename on your disk.
you can use os.rename() to actully apply the changes to your files:
all_files = glob.glob("*.pdf")
for i in all_files:
fname = os.path.splitext(os.path.basename(i))[0]
fname = fname.replace("-00","-000")
os.rename(i, os.path.join(os.path.dirname(i), fname ))
I have a code that recursively changes all the files with .py extension to .txt inside a folder.
which is :
def frm_ext_to_ext(directory, from_ext, to_ext):
"""
directory, from_ext, to_ext should be passed as strings including '.'
For example : directory = '/home/Desktop/folder/file', from_ext = '.txt' , to_ext = '.py'
"""
for foldername, subfolders, filenames in os.walk(directory):
for f in filenames :
if f.endswith('.py'):
base = os.path.splitext(f)[0]
os.rename(os.path.join(foldername, f), os.path.join(foldername, base + to_ext))
But what I want is to change the filename like :
If a file name is script.py, I want it to be changed as script_py.txt to every file extension and I want another function to reverse this change i.e from script_py.txt to script.py.
Note : Above .py was just an example. The extension could be anything like, .pynb etc
Also, If the extension is already .txt, I want it as it is. Any help ?
I hope this is what you want
For more safety, you should do a script that check if there is a file contains more than one '.'
def frm_ext_to_ext(directory, from_ext, to_ext):
for foldername, subfolders, filenames in os.walk(directory):
for f in filenames :
ext = f.split('.')[1]
if(ext!='txt' and to_ext == 'txt'):
base = f.split('.')[0]
os.rename(os.path.join(foldername, f), os.path.join(foldername, base + '_' + ext + '.' + to_ext))
elif(ext=='txt' and to_ext!='txt'):
base=f.split('_')[0]
os.rename(os.path.join(foldername, f), os.path.join(foldername, base + '.' + to_ext))
Usage:
frm_ext_to_ext(DIR, 'py', 'txt')
frm_ext_to_ext(DIR, 'txt', 'py')
since extensions are added after dot character in a filename, we can split the file_name with "." using file_name.split(".") and append last element with file name.
For example i have following files in my "D:\FlaskApp" directory
app.py
runApp.bat
demo.html
index.html
using split to append the extension:
import os
directory = "D:\FlaskApp"
for foldername, subfolders, filenames in os.walk(directory):
for f in filenames :
fl = f.split(".")
print(fl[0] + "_" + fl[-1])
this gives:
app_py
runApp_bat
demo_html
index_html
I have some files in a folder named like this test_1999.0000_seconds.vtk. What I would like to do is to is to change the name of the file to test_1999.0000.vtk.
You can use os.rename
os.rename("test_1999.0000_seconds.vtk", "test_1999.0000.vtk")
import os
currentPath = os.getcwd() # get the current working directory
unWantedString = "_seconds"
matchingFiles =[]
for path, subdirs, files in os.walk(currentPath):
for f in files:
if f.endswith(".vtk"): # To group the vtk files
matchingFiles.append(path+"\\"+ f) #
print matchingFiles
for mf in matchingFiles:
if unWantedString in mf:
oldName = mf
newName = mf.replace(unWantedString, '') # remove the substring from the string
os.rename(oldName, newName) # rename the old files with new name without the string
I have a folder with a list of files without extensions, I need to rename or create an extension to each file ".text"
This is my code, but there is a small bug, the second time I run the code the files renamed again with a long name ,, for example
The file name : XXA
after first run : XXA.text
second : XXAXXA.text.text
import os
def renamefiles():
filelist = os.listdir(r"D:\")
print(filelist)
os.chdir(r"D:\")
path = os.getcwd()
for filename in filelist:
print("Old Name - "+filename)
(prefix, sep, sffix) = filename.rpartition(".")
newfile = prefix + filename + '.text'
os.rename(filename, newfile)
print("New Name - "+newfile)
os.chdir(path)
rename_files()
Where you have
newfile = prefix + '.text'
You can have
if not file_name.contains(".text"):
newfile = prefix + file_name + '.text'
Note where you have newfile = prefix + file_name + '.text', I changed it to newfile = prefix + '.text'. If you think about it, you don't need filename when you have already extracted the actual file name into prefix.
for file in os.listdir(os.curdir):
name, ext = os.path.splitext(file)
os.rename(file, name + ".text")
Don't do the partitioning that way, use os.path.splitext:
file_name, extension = os.path.splitext(filename)
if not extension:
newfile = file_name + '.text'
os.rename(filename, newfile)
If the file has no extension splitext returns '' which is Falsy. The file extension can then be changed.
import os
def renamefiles():
filelist = os.listdir(r"D:\")
print(filelist)
os.chdir(r"D:\")
path = os.getcwd()
for filename in filelist:
print("Old Name - "+filename)
(prefix, sep, sffix) = filename.rpartition(".")
newfile = prefix + filename + '.text'
if not filename.endswith(".text"):
os.rename(filename, newfile)
print("New Name - "+newfile)
os.chdir(path)
renamefiles()
You need to check if the filename ends with .text, and skip those
So I'm trying to iterate through a list of files that are within a subfolder named eachjpgfile and change the file from doc to the subfolder eachjpgfile mantaining the file's name but when I do this it adds the file to directory before eachjpgfile rather than keeping it in it. Looking at the code below, can you see why is it doing this and how can I keep it in the eachjpgfile directory?
Here is the code:
for eachjpgfile in filelist:
os.chdir(eachjpgfile)
newdirectorypath = os.curdir
list_of_files = os.listdir(newdirectorypath)
for eachfile in list_of_files:
onlyfilename = os.path.splitext(eachfile)[0]
if onlyfilename == 'doc':
newjpgfilename = eachfile.replace(onlyfilename,eachjpgfile)
os.rename(eachfile, newjpgfilename)
There is a lot of weird stuff going on in here, but I think the one that's causing your particular issue is using 'eachjpgfile' in 'eachfile.replace'.
From what I can tell, the 'eachjpgfile' you're passing in is a full-path, so you're replacing 'doc' in the filename with '/full/path/to/eachjpgfile', which puts it parallel to the 'eachjpgfile' directory regardless of your current working directory.
You could add a line to split the path/file names prior to the replace:
for eachjpgfile in filelist:
os.chdir(eachjpgfile)
newdirectorypath = os.curdir
list_of_files = os.listdir(newdirectorypath)
for eachfile in list_of_files:
onlyfilename = os.path.splitext(eachfile)[0]
if onlyfilename == 'doc':
root, pathName= os.path.split(eachjpgfile) #split out dir name
newjpgfilename = eachfile.replace(onlyfilename,pathName)
os.rename(eachfile, newjpgfilename)
which is a very dirty fix for a very dirty script. :)
try this:
import os
path = '.'
recursive = False # do not descent into subdirs
for root,dirs,files in os.walk( path ) :
for name in files :
new_name = name.replace( 'aaa', 'bbb' )
if name != new_name :
print name, "->", new_name
os.rename( os.path.join( root, name),
os.path.join( root, new_name ) )
if not recursive :
break