Rename substring of actual files - python - python

I am reading in all the files in a given folder:
import os
path = '/Users/user/Desktop/folder_name'
files = os.listdir(path)
I have multiple files (100+) with the following names:
20220330_a.txt 20220330_b.txt 20220330_c.txt
I want to replace the "20220331" to "20220630" in the actual file names in the folder, so I obtain 20220630_a.txt, 20220630_b.txt etc.
Any ideas?

I figured it out myself:
old_date = "20200331"
new_date = "20200630"
for file in os.listdir(path):
if file.startswith(old_date):
if file.find(old_date) > -1:
counter = counter + 1
os.rename(os.path.join(path, file), os.path.join(path, file.replace(old_date,new_date)))
if counter == 0:
print("No file has been found")

Related

Rename multiple files by removing filename prefix

I'm new to Python, I have multiple files in a folder where I need to rename those files as the the given pattern.
Example:
Folder : /Users/Usr1/Documents/FilesFolder and
File's :
0. a101.employee.txt
1. a101.department.txt
2. a101.salary.txt
I want to remove the prefix of the file till a101 and rename to empoloyee.txt/salary.txt.
Expected Output:
My try:
import os
path = '/Users/User1/Documents/FilesFolder'
files = os.listdir(path)
for index, file in enumerate(files):
os.rename(os.path.join(path, file), os.path.join(path,file.removeprefix('a101')))
But unable to get expected result.
You may use regular expression:
import os
import re
path = '/Users/User1/Documents/FilesFolder'
files = os.listdir(path)
p = ".*a101.(.+)"
for file in files:
m = re.match(p, file)
if m is not None:
file_new = m.group(1)
print(file_new)
I think this can solve your problem
import os
import glob
# directory Path
path = "/path/to/dir"
# move to directory
os.chdir(path)
# Getting all files in the directory which contains a101
files = glob.glob("*a101*")
for file in files:
splitted = file.split('.')
filename, ext = splitted[-2], splitted[-1]
new_name = f"{filename}.{ext}"
os.rename(file, new_name)
If your file name is following same pattern with 3 . then you can use this for renaming. removeprefix is introduced in python 3.9.
files = ["0. a101.employee.txt", "1. a101.department.txt" ,"2. a101.salary.txt"]
for file in files:
print(".".join(file.split(".")[-2:]))
output:
employee.txt
department.txt
salary.txt
i can suggest you:
files = ["0. a101.employee.txt", "1. a101.department.txt" ,"2. a101.salary.txt"]
for index, file in enumerate(files):
filename = file.split(".")
print(filename[2]+"."+filename[3])
I got the followingoutput:
employee.txt
department.txt
salary.txt

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()

how can i find the no.of files with a list of target extensions eg:.txt, .pdf etc and print it separately for current and sub directories using python

import os
def fileCount(folder):
"count the number of files in a directory"
count = 0
for filename in os.listdir(folder):
path = os.path.join(folder, filename)
if os.path.isfile(path):
count += 1
elif os.path.isdir(path):
count += fileCount(path)
print(folder,'having',count)
return count
fileCount('.')
import glob
def countMe(MyPath,typeofFile):
numInstances = len(glob.glob1(MyPath,'*.'+typeofFile))
return numInstances
typeofFile should be a string of the extension you are looking for. If you are looking for .pdf then typeofFile = 'pdf'

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

not listing entire directory

Im new on Python, Im actually on a short course this week, but I have a very specific request and I dont know how to deal with it right now: I have many different txt files in a folder, when I use the following code I receive only the filename of two of the many files, why is this?
regards!
import dircache
lista = dircache.listdir('C:\FDF')
i = 0
check = len(lista[0])
temp = []
count = len(lista)
while count != 0:
if len(lista[i]) != check:
temp.append(lista[i- 1])
check = len(lista[i])
else:
i = i + 1
count = count - 1
print (temp)
Maybe you can use the glob library: http://docs.python.org/2/library/glob.html
It seems that it works UNIX-like for listing files so maybe it can work with this?
import glob
directory = 'yourdirectory/'
filelist = glob.glob(directory+'*.txt')
If I've understood you correct, you would like to get all files?
Try it in this case:
import os
filesList = None
dir = 'C:\FDF'
for root, dirs, files in os.walk(dir):
filesList = files
break
print(filesList)
If need full path use:
import os.path
filesList = None
dir = 'C:\FDF'
for root, dirs, files in os.walk(dir):
for file in files:
filesList.append(os.path.join(root, file))
print(filesList)

Categories