I want to rename some of my files using python.
The script should sort all files using date and add 1,2,3,... before actual file names.
Actual file name should not be changed.
Try this:
from os import listdir, rename
from os.path import getmtime
path = 'your_path'
filesName = listdir(path)
filesName.sort(key=lambda fileName: getmtime(path + fileName))
i=1
for fileName in filesName:
rename(path + fileName, path + str(i) + fileName)
i +=1
Related
There is a directory in C:\Users\abcd\video
Inside the directory, there are a lot of .mp4 files.
How do I rename all .mp4 files based on an Excel sheet that contains following information using Python:
For example, the current filename is A.mp4. I would like to rename it to 1.mp4.
Note:
If you want to use an Excel file, with the extension .xlsx
After installing xlrd, i.e. a dependency for reading .xlsx files using the follwing command from the command line:
pip install xlrd
Code:
import os
import pandas as pd
# Read your renaming data
dst = pd.read_excel('C:\\Users\\abcd\\video\\map.xlsx', header=None)
# Create a dictionary for easier access
dictionary = dict(zip(list(dst[dst.columns[0]]), list(dst[dst.columns[1]])))
# Renaming if filename ends with .mp4
for filename in os.listdir("C:\\Users\\abcd\\video"):
if (filename.endswith(".mp4")):
dest = str(dictionary[filename[:-4]]) + ".mp4"
src = "C:\\Users\\abcd\\video\\" + filename
dst = "C:\\Users\\abcd\\video\\" + dest
os.rename(src, dest)
Edit2:
Can use python3.4+ Path/pathlib to iterate recursively throught any folder
import os
import pandas as pd
from pathlib import Path
root = "C:\\Users\\abcd\\video\\"
# Read your renaming data
dst = pd.read_excel('C:\\Users\\abcd\\video\\map.xlsx', header=None)
# Create a dictionary for easier access
dictionary = dict(zip(list(dst[dst.columns[0]]), list(dst[dst.columns[1]])))
# Recursively reading all .mp4 files
files = list(Path(root).glob('**/*.mp4'))
for filename in files:
src = str(filename)
if(src[:src.rindex('\\')]==root):
dest = src[:src.rindex('\\')] + str(dictionary[str(filename)[str(filename).rindex('\\')+1:-4]]) + ".mp4"
else:
dest = src[:src.rindex('\\')] + "\\" + str(dictionary[str(filename)[str(filename).rindex('\\')+1:-4]]) + ".mp4"
os.rename(src, dest)
To solve your problem you can use the following approach (string formatting for python 3.6+):
import glob
import os
import pandas as pd
def rename_files(parent_dir, files_extension, filenames_map):
"""
Rename files with specified extension located in subfolders of parent directory
:param parent dir: Path to subfolder's parent directory
:param files_extension: Renaming file's extension
:param filenames_map: Mapping from initial filenames to target filenames
:return: None
"""
files_template = os.path.join(parent_dir, f'**/*{files_extension}')
files = glob.glob(pathname=files_template, recursive=True)
for file_path in files:
base_dir, filename_with_ext = os.path.split(file_path)
filename, extension = os.path.splitext(filename_with_ext)
try:
new_filename = filenames_map[filename]
except KeyError:
raise Exception(f"There's no {filename} key in filenames mapping")
new_file_path = os.path.join(base_dir, f'{new_filename}{extension}')
os.rename(file_path, new_file_path)
filenames_map_file_path = r'C:\Users\abcd\video\filenames_map.xlsx'
parent_files_dir_path = r'C:\Users\abcd\video'
extension = '.mp4'
filenames_map = pd.read_excel(io=filenames_map_file_path, header=None) \
.set_index(0)[1] \
.to_dict()
rename_files(parent_dir=parent_files_dir_path,
files_extension=extension,
filenames_map=filenames_map)
excerpt from my python script located at C:\Users\my_name\documents\python_projects\randomness\random.py :
some_number = 3452342
filename = str(some_number) + '.csv'
# file 3452342.csv is stored in C:\Users\my_name\documents\python_projects\randomness\history
# call a function that takes the filename as the parameter
my_func(r'history\filename')
It triggers the following error:
FileNotFoundError: [Errno 2] File b'history\filename' does not exist: b'history\filename'
what exactly is going wrong here?
How can I pass the filename to my_func when it is located in a sub-folder?
thanks in advance
The answer to your question what's going wrong:
Python tried to open the file with the name literally "filename" in the subdirectory named "history", which is doesn't exist. You should pass the filename variable's value instead as follows:
You should use os.path.join().
import os
some_number = 3452342
filename = str(some_number) + '.csv'
workdir = "C:\Users\my_name\documents\python_projects\randomness\history"
my_func(os.path.join(workdir, filename))
Or if the file 3452342.csv placed in a subfolder (called history) of the the main script's directory, then you can use:
import os
some_number = 3452342
filename = str(some_number) + '.csv'
my_func(os.path.join("history", filename))
Alternatively you can simply use string concatenation:
import os
some_number = 3452342
filename = str(some_number) + '.csv'
my_func("history/" + filename)
Another approach using Python's format():
import os
some_number = 3452342
filename = str(some_number) + '.csv'
my_func("history/{}".format(filename))
First try to get the current path then join the path you got with the name of your file.
import os
some_number = 3452342
filename = str(some_number) + '.csv'
path_file = os.path.join(os.getcwd(), filename)
my_func(path_file)
for more about how to work with path using python check out this.
Common pathname manipulations
First, to be platform independent you should use os.path.join to concatenate directories.
Second, like #k88 pointed out, you need to pass the variable filename into your path, not the string 'filename'
The clean way would be:
import os
some_number = 3452342
filename = str(some_number) + '.csv'
# file 3452342.csv is stored in C:\Users\my_name\documents\python_projects\randomness\history
# call a function that takes the filename as the parameter
my_func(os.path.join('history', filename))
Relative Or Absolute Path?
If your history subfolder is a fixed subfolder of your script's directory, you should even consider to determine your target filename as an absolute path like this (see also this answer with comments):
base_dir = os.path.dirname(os.path.abspath(__file__))
my_func(os.path.join(base_dir, 'history', filename))
I want to Make a Python program that takes a folder name from the input argument, and then renames all its files by adding an "_{n}" at the end of it where n is the serial of that file. For example, if folder "images" contained, "images/cat.jpg", "images/dog.jpg", then after running the command, it will have "images/cat_1.jpg", "images/dog_2.jpg" . Sort the files according to last accessed date. I tried the problem partially as following:-
import os
from os import rename
from os.path import basename
path = os.getcwd()
filenames =next(os.walk(path))[2]
countfiles=len(filenames)
for filename in filenames:
fname=os.path.splitext(filename)[0]
ext=os.path.splitext(filename)[1]
old=fname+ext
new=fname + '_' +ext
os.rename(old, new)
this can rename the file adding an under score at the end of file name.However, I have no idea to add serial of files after the underscore. I would like to know how to batch rename the files using a simple Python script. I would appreciate any advice.
Thank you!
Have you tried something like:
import os
filepath = 'C:/images/'
os.chdir(filepath)
for num, filename in enumerate(os.listdir(os.getcwd()), start= 1):
fname, ext = filename, ''
if '.' in filename:
fname, ext = filename.split('.')
os.rename(filename, fname + '_%s' %num + '.' + ext)
I am new to Python coding so here a question. I want to find files that are called "untitled" with any kind of extension, e.g. jpg, indd, psd. Then rename them to the date of the current day.
I have tried the following:
import os
for file in os.listdir("/Users/shirin/Desktop/Artez"):
if file.endswith("untitled.*"):
print(file)
When I run the script, nothing happens.
You might find the glob function more useful in this situation:
import glob
for file in glob.glob("/Users/shirin/Desktop/Artez/untitled.*"):
print(file)
Your function does not print anything as there are probably no files ending with .* in the name. The glob.glob() function will carry out the file expansion for you.
You can then use this to do your file renaming as follows:
import glob
import os
from datetime import datetime
current_day = datetime.now().strftime("%Y-%m-%d")
for source_name in glob.glob("/Users/shirin/Desktop/Artez/untitled.*"):
path, fullname = os.path.split(source_name)
basename, ext = os.path.splitext(fullname)
target_name = os.path.join(path, '{}{}'.format(current_day, ext))
os.rename(source_name, target_name)
A Python datetime object can be used to get you a suitable timestamp.
Python string comparator does not support wildcards. You can search for "untitled." anywhere in the text:
import os
for file in os.listdir("/Users/shirin/Desktop/Artez"):
if "untitled." in file:
print(file)
keep in mind that this will include any file that has "untitled." at any location of the file.
try with this approach
import os
directoryPath = '/Users/shirin/Desktop/Artez'
lstDir = os.walk(directoryPath)
for root, dirs, files in lstDir:
for fichero in files:
(filename, extension) = os.path.splitext(fichero)
if filename.find('untitle') != -1: # == 0 if starting with untitle
os.system('mv '+directoryPath+filename+extension+' '+directoryPath+'$(date +"%Y_%m_%d")'+filename+extension)
import os
for file in os.listdir("/Users/shirin/Desktop/Artez"):
if(file.startswith("untitled")):
os.rename(file, datetime.date.today().strftime("%B %d, %Y") + "." + file.split(".")[-1])
i have a folder with a lot of files like that:
2012-05-09.txt
2012-05-10.txt
2012-05-11.txt
etc.
now i wanna delete the hyphen and add " _PHOTOS_LOG " that it looks in the end like this:
20120509_PHOTOS_LOG.txt
20120510_PHOTOS_LOG.txt
20120511_PHOTOS_LOG.txt
etc.
How to do ?
thats the code now:
//updated the code, now its working
import os
import glob
import os.path
import sys
src = 'D:\\testing/hyphen1'
src = r'D:\testing\test'
for fn in os.listdir(src):
new_filename = fn.replace('-','').replace('.txt', '_PHOTOS_LOG.txt')
fn = os.path.join(src, fn)
new_filename = os.path.join(src, new_filename)
try:
os.rename(fn, new_filename)
except (WindowsError, OSError):
print 'Error renaming "%s" to "%s"' % (fn, new_filename)
print sys.exc_info()[1]
You could do the rename something like this:
import os
for filename in os.listdir("."):
if filename.endswith(".txt"):
newFilename = filename.replace("-", "")
os.rename(filename, newFilename[:7]+"_PHOTO_LOG.txt")
os.listdir(".") returns the names of the entries in the current folder
filename.endswith(".txt") verifies if the filename is one of your text files
if it is, it removes the - and adds the _PHOTO_LOG at the end
new_filename = old_filename.replace("-", "").replace(".txt", "_PHOTOS_LOG.txt")
That will get you the new filename, if you want to rename all the files, then:
import os
for old_filename in os.listdir("."):
new_filename = old_filename.replace("-", "").replace(".txt", "_PHOTOS_LOG.txt")
os.rename(old_filename, new_filename)
For all of your files in your current directory:
import os
for fn in os.listdir('.'):
new_filename = fn.replace('-','').replace('.txt', '_PHOTOS_LOG.txt')
os.rename(fn, new_filename)
Using os.rename() to change the filenames.
The individual file names will end up a series of strings, so while you usually would want to use methods from the os module, you can simply treat these as strings since you are not looking at paths, but simple filenames and use replace() to create the new names.
--
Example for one filename to show transformation:
fn ='2012-05-09.txt'
then
fn.replace('-','').replace('.txt', '_PHOTOS_LOG.txt')
will yield '20120509_PHOTOS_LOG.txt'
You need to iterate through the list of files
and rename them according to your needs:
import os
import glob
for name in glob.glob('*.txt'):
newname = "%s_PHOTOS_LOG.txt" % name.replace('-','')[:-4]
os.rename(name, newname)
The glob.glob function produces a list of .txt files in the current directory.