Is there an easy way to rename a group of files already contained in a directory, using Python?
Example: I have a directory full of *.doc files an
If you don't mind using regular expressions, then this function would give you much power in renaming files:
import re, glob, os
def renamer(files, pattern, replacement):
for pathname in glob.glob(files):
basename= os.path.basename(pathname)
new_filename= re.sub(pattern, replacement, basename)
if new_filename != basename:
os.rename(
pathname,
os.path.join(os.path.dirname(pathname), new_filename))
So in your example, you could do (assuming it's the current directory where the files are):
renamer("*.doc", r"^(.*)\.doc$", r"new(\1).doc")
but you could also roll back to the initial filenames:
renamer("*.doc", r"^new\((.*)\)\.doc", r"\1.doc")
and more.
I had a similar problem, but I wanted to append text to the beginning of the file name of all files in a directory and used a similar method. See example below:
folder = r"R:\mystuff\GIS_Projects\Website\2017\PDF"
import os
for root, dirs, filenames in os.walk(folder):
for filename in filenames:
fullpath = os.path.join(root, filename)
filename_split = os.path.splitext(filename) # filename will be filename_split[0] and extension will be filename_split[1])
print fullpath
print filename_split[0]
print filename_split[1]
os.rename(os.path.join(root, filename), os.path.join(root, "NewText_2017_" + filename_split[0] + filename_split[1]))
as to me in my directory I have multiple subdir, each subdir has lots of images I want to change all the subdir images to 1.jpg ~ n.jpg
def batch_rename():
base_dir = 'F:/ad_samples/test_samples/'
sub_dir_list = glob.glob(base_dir + '*')
# print sub_dir_list # like that ['F:/dir1', 'F:/dir2']
for dir_item in sub_dir_list:
files = glob.glob(dir_item + '/*.jpg')
i = 0
for f in files:
os.rename(f, os.path.join(dir_item, str(i) + '.jpg'))
i += 1
(mys own answer)https://stackoverflow.com/a/45734381/6329006
directoryName = "Photographs"
filePath = os.path.abspath(directoryName)
filePathWithSlash = filePath + "\\"
for counter, filename in enumerate(os.listdir(directoryName)):
filenameWithPath = os.path.join(filePathWithSlash, filename)
os.rename(filenameWithPath, filenameWithPath.replace(filename,"DSC_" + \
str(counter).zfill(4) + ".jpg" ))
# e.g. filename = "photo1.jpg", directory = "c:\users\Photographs"
# The string.replace call swaps in the new filename into
# the current filename within the filenameWitPath string. Which
# is then used by os.rename to rename the file in place, using the
# current (unmodified) filenameWithPath.
# os.listdir delivers the filename(s) from the directory
# however in attempting to "rename" the file using os
# a specific location of the file to be renamed is required.
# this code is from Windows
Such renaming is quite easy, for example with os and glob modules:
import glob, os
def rename(dir, pattern, titlePattern):
for pathAndFilename in glob.iglob(os.path.join(dir, pattern)):
title, ext = os.path.splitext(os.path.basename(pathAndFilename))
os.rename(pathAndFilename,
os.path.join(dir, titlePattern % title + ext))
You could then use it in your example like this:
rename(r'c:\temp\xx', r'*.doc', r'new(%s)')
The above example will convert all *.doc
files in c:\temp\xx
dir to new(%s).doc
, where %s
is the previous base name of the file (without extension).
Be in the directory where you need to perform the renaming.
import os
# get the file name list to nameList
nameList = os.listdir()
#loop through the name and rename
for fileName in nameList:
rename=fileName[15:28]
os.rename(fileName,rename)
#example:
#input fileName bulk like :20180707131932_IMG_4304.JPG
#output renamed bulk like :IMG_4304.JPG