I'm trying to rename files in a directory so that it the new name is the original name followed by a space + "17-" + an incrementally increasing number.
The code below is just renaming files from 151, upward. How do I keep the original name, adding the text "17-" and the numbers?
import os
path = 'C:\Users\dcs\Desktop\Test direct'
files = os.listdir(path)
i = 151
for file in files:
os.rename(os.path.join(path, file), os.path.join(path, str(i)+'.TIF'))
i = i+1
Simply by writing that concatenation expression. If I understand your details correctly, your new loop body would be
new_name = file + " 17-" + str(i) + ".TIF"
os.rename(os.path.join(path, file),
os.path.join(path, new_name) )
i += 1
This would change file "ABC" into file "ABC 17-151.TIF"; the next would contain "17-152", and so on.
FACEPALM
file is a built-in type. Change the loop index.
for fname in files:
new_name = fname + " 17-" + str(i) + ".TIF"
os.rename(os.path.join(path, fname), new_name)
i += 1
If I understand Prune's suggestion above, which I obviously don't, it would look like:
import os
path = 'C:\Users\dcs\Desktop\Test direct'
files = os.listdir(path)
i = 151
#The part that I want to strip the extensions from
for file in files:
new_name = file[:-3]
#The part that words correctly (thanks Prune)
for fname in files:
new_name = fname + " 17-" + str(i) + ".TIF"
os.rename(os.path.join(path, fname), new_name)
i += 1
However the first part, meant to strip the file of it's extension isn't working.
Related
I have to change the name of several files in a folder such as:
CO201_LF.ab1
CO202_LF.ab1
CO034_LF.ab1
CO9871_LF.ab1
CO9576_LF.ab1
And replace those names with the names that I have in a list in a txt file.
How I can do that?
For the moment I have tried this without good results:
import os, fnmatch
def change_name():
file_path = '/home/SCRIPT_BIO/thesis_CSU/rbcL_LF_consolidated/ab1_RAW/'>
files_to_rename = fnmatch.filter(os.listdir(file_path), '*.ab1')
print(files_to_rename)
new_name = '/home/SCRIPT_BIO/thesis_CSU/rbcL_LF_consolidated/ab1_RAW/spp_list.txt/'>
for i, file_name in enumerate(files_to_rename):
new_file_name = new_name + str(i) + '.ab1'
os.rename(file_path + file_name,
file_path + new_file_name)
if __name__ == '__main__':
change_name()
The message that I have gotten is this:
"FileNotFoundError: [Errno 2] No such file or directory: '/home/SCRIPT_BIO/thesis_CSU/rbcL_LF_consolidated/ab1_RAW/CO201_LF.ab1' -> '/home/SCRIPT_BIO/thesis_CSU/rbcL_LF_consolidated/ab1_RAW//home/SCRIPT_BIO/thesis_CSU/rbcL_LF_consolidated/ab1_RAW/spp_list.txt0'"
What I want to get or the final product that I expect to get are those files (CO201_LF.ab1, etc.) renamed by the names in that list (spp_list.txt) in the same order.
Aegiphylla monica.ab1
Eugenia edulis.ab1
Miconia sparata.ab1
Deutemia claricia.ab1
Drapteris lineata,ab1
Maybe someone can help me?
Indent the os.rename() to be part of the "for" loop.
def change_name():
file_path = '/home/SCRIPT_BIO/thesis_CSU/rbcL_LF_consolidated/ab1_RAW/'>
files_to_rename = fnmatch.filter(os.listdir(file_path), '*.ab1')
print(files_to_rename)
new_name = '/home/SCRIPT_BIO/thesis_CSU/rbcL_LF_consolidated/ab1_RAW/spp_list.txt/'>
for i, file_name in enumerate(files_to_rename):
new_file_name = new_name + str(i) + '.ab1'
os.rename(file_path + file_name,
file_path + new_file_name)
if __name__ == '__main__':
change_name()
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()]))
Python novice, my simple script gets a given directory and renames all files sequentially, however it is deleting the files but the print is showing the files names getting renamed, not sure where its going wrong here.
Also, in what order does it retrieve these files?
import os
path = os.path.abspath("D:\Desktop\gp")
i = 0
for file_name in os.listdir(path):
try:
print (file_name + " - " + str(i))
os.rename(os.path.join(path,file_name), str(i))
except WindowsError:
os.remove(str(i))
os.rename(os.path.join(path,file_name), str(i))
i += 1
print(str(i) + " files.")
Edit
Below is the solution with working code, retrieves all files in a dir by creation date and assigns them a iterated number while retaining file extension.
import os
def sorted_dir(folder):
def getctime(name):
path = os.path.join(folder, name)
return os.path.getctime(path)
return sorted(os.listdir(path), key=getctime)
path = os.path.abspath("D:\Path\Here")
i = 0
for file_name in sorted_dir(path):
_, ext = os.path.splitext(file_name)
print (file_name + " - " + str(i)+ext)
os.rename(os.path.join(path,file_name), os.path.join(path, str(i) + ext))
i += 1
print(str(i-1) + " files.")
The problem is that you're using an absolute path for the source, but a relative path for the destination. So the files aren't getting deleted, they're just getting moved into the current working directory.
To fix it so they get renamed into the same directory they were already in, you can do the same thing on the destination you do on the source:
os.rename(os.path.join(path,file_name), os.path.join(path, str(i)))
From a comment, it sounds like you may want to preserve the extensions on these files. To do that:
_, ext = os.path.splitext(file_name)
os.rename(os.path.join(path,file_name), os.path.join(path, str(i) + ext))
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
My program cannot find the path that it just made, the program is for sorting files in the download folder.
If it finds a new type of file it should make a folder for that file type.
import os
FileList = os.listdir("/sdcard/Download/")
for File in FileList:
#print File
extension = ''.join(os.path.splitext(File)[1])
ext = extension.strip('.')
if os.path.exists("/mnt/external_sd/Download/" + ext):
Data = open("/sdcard/Download/" + File, "r").read()
file("/mnt/external_sd/" + ext + "/" + File, "w").write(Data)
elif os.path.exists("/mnt/external_sd/Download/" + ext) != True:
os.makedirs("/mnt/external_sd/Download/" + ext)
Data = open("/sdcard/Download/" + File, "r").read()
file("/mnt/external_sd/" + ext + "/" + File, "w").write(Data)
You create the directory
"/mnt/external_sd/Download/" + ext
but then you are trying to write to
"/mnt/external_sd/" + ext + "/" + File
You dropped the Download folder in that path. Change the last line to:
file("/mnt/external_sd/Download/" + ext + "/" + File, "w").write(Data)
Incidentally, it would be a bit shorter and clearer to write your last seven lines by taking the shared lines out of the if else statement and using shutil.copy instead of reading in the whole file then writing it out again:
import shutil
if not os.path.exists("/mnt/external_sd/Download/" + ext):
os.makedirs("/mnt/external_sd/Download/" + ext)
shutil.copy("/sdcard/Download/" + File, "/mnt/external_sd/Download/" + ext + "/" + File)
(Using shutil will also generally be faster and use less memory, especially if your files are large).