System cannot find the file specified when renaming image files - python

I have more than 1000 JPG images in a folder having different name. I want to rename images as 0.JPG, 1.jpg, 2.jpg...
I tried different code but having below error:
The system cannot find the file specified: 'IMG_0102.JPG' -> '1.JPG'
The below code is one the codes found in this link: Rename files sequentially in python
import os
_src = "C:\\Users\\sazid\\Desktop\\snake"
_ext = ".JPG"
for i,filename in enumerate(os.listdir(_src)):
if filename.endswith(_ext):
os.rename(filename, str(i)+_ext)
How to solve this error. Any better code to rename image files in sequential order?

os.listdir only returns the filenames, it doesn't include the directory name. You'll need to include that when renaming. Try something like this:
import os
_src = "C:\\Users\\sazid\\Desktop\\snake"
_ext = ".JPG"
for i,filename in enumerate(os.listdir(_src)):
if filename.endswith(_ext):
src_file = os.path.join(_src, filename)
dst_file = os.path.join(_src, str(i)+_ext)
os.rename(src_file, dst_file)

just use glob and save yourself the headache
with glob your code turns into this:
import os
from glob import glob
target_dir = './some/dir/with/data'
for i, p in enumerate(glob(f'{target_dir}/*.jpg')):
os.rename(p, f'{target_dir}/{i}.jpg')
in this code glob() gives you a list of found file paths for files that have the .jpg extension, hence the *.jpg pattern for glob, here is more on glob

Related

Printing full path to all possible png files in directory

I need to display all png files in directory 'images'. The problem is there is subdirectory 'additional files' with one more png in it.
import glob
my_path = "images"
possible_files = os.path.join(my_path, "*.png")
for file in glob.glob(possible_files):
print(file)
How can i display full path to all png files in this directory including png files in subdirectories without new loop?
You can use os.walk method.
import glob
import os
for (dirpath, dirnames, filenames) in os.walk(YOURPATH):
possible_files = os.path.join(dirpath, "*.png")
for file in glob.glob(possible_files):
print(file)
'filenames' gives you the name of the files and you can use 'dirpath' to and 'dirnames' to determine which directory they are from, so you can even include some sub directories and skip others.
How about this? You are already using the os library.
my_path = "images"
out = [os.path.abspath(x) for x in glob.glob(my_path+"\\**\\*.png", recursive=True)]
out is a list with all png files with fullpath (with subdirectories)

Opening images from a directory from a list of filenames

I want to be able to open/move/rename the images form a list of filenames from a directory with hundreds of images. Unfortunately there are no wildcards, they are all .jpg and the images names are not sequential.
e.g
list = ['media\\1520298987567.jpg',
'media\\1520298997109.jpg',
'media\\1520299004063.jpg',
'media\\1520299010082.jpg',
'media\\1520299015452.jpg',
'media\\1520299020690.jpg',
'media\\1520299026092.jpg']
Does anyone know how to do this?
Thank you in advance.
This may help you, (open/ move/ rename) the image files.
from PIL import Image
import glob, os
path = '/path/to/move/'
list_of_files = ['testfile1.jpg', 'testfile2.jpg']
for infile in glob.glob("*.jpg"):
filename, ext = os.path.splitext(infile)
if filename + '.' + ext in list_of_files:
# Open the image
im = Image.open(image_path)
# Rename the Image
renamed_filename = filename + '_renamed.' + ext
# Move the image
im.save(path + renamed_filename, 'jpg')
You can use glob package in python to get list of jpg files and os package to perform open/move/rename operations
import glob
list_of_files = glob.glob("media/*.jpg"):
for file in list_of_files:
# do required operation with the help of os package

How to move from one directory to another and delete only '.html' files in python?

I attended an interview and they asked me to write a script to move from one directory to another and delete only the .html files.
Now I tried to do this at first using os.remove() . Following is the code:
def rm_files():
import os
from os import path
folder='J:\\Test\\'
for files in os.listdir(folder):
file_path=path.join(folder,files)
os.remove(file_path)
The problem I am facing here is that I cannot figure out how to delete only .html files in my directory
Then I tried using glob. Following is the code:
def rm_files1():
import os
import glob
files=glob.glob('J:\\Test\\*.html')
for f in files:
os.remove(f)
Using glob I can delete the .html files but still I cannot figure out how to implement the logic of moving from one directory to another.
And along with that can someone please help me figure out how to delete a specific file type using os.remove() ?
Thank you.
Either of these methods should work. For the first way, you could just string.endswith(suffix) like so:
def rm_files():
import os
from os import path
folder='J:\\Test\\'
for files in os.listdir(folder):
file_path=path.join(folder,files)
if file_path.endswith(".html"):
os.remove(file_path)
Or if you prefer glob, moving directories is fairly straightforward: os.chdir(path) like this:
def rm_files1():
import os
os.chdir('J:\\Test')
import glob
files=glob.glob('J:\\Test\\*.html')
for f in files:
os.remove(f)
Though it seems unnecessary since glob is taking an absolute path anyway.
Your problem can be described in the following steps.
move to specific directory. This can be done using os.chdir()
grab list of all *.html files. Use glob.glob('*.html')
remove the files. use os.remove()
Putting it all together:
import os
import glob
import sys
def remove_html_files(path_name):
# move to desired path, if it exists
if os.path.exists(path_name):
os.chdir(path_name)
else:
print('invalid path')
sys.exit(1)
# grab list of all html files in current directory
file_list = glob.glob('*.html')
#delete files
for f in file_list:
os.remove(f)
#output messaage
print('deleted '+ str(len(file_list))+' files in folder' + path_name)
# call the function
remove_html_files(path_name)
To remove all html files in a directory with os.remove() you can do like this using endswith() function
import sys
import os
from os import listdir
directory = "J:\\Test\\"
test = os.listdir( directory )
for item in test:
if item.endswith(".html"):
os.remove( os.path.join( directory, item ) )

How can I copy all files from all subfolders of a folder to another folder in Python? [duplicate]

I want to copy all my JPG files in one directory to a new directory.
How can I solve this in Python?I just start to learn Python.
Thanks for your reply.
Of course Python offers all the tools you need. To copy files, you can use shutil.copy(). To find all JPEG files in the source directory, you can use glob.iglob().
import glob
import shutil
import os
src_dir = "your/source/dir"
dst_dir = "your/destination/dir"
for jpgfile in glob.iglob(os.path.join(src_dir, "*.jpg")):
shutil.copy(jpgfile, dst_dir)
Note that this will overwrite all files with matching names in the destination directory.
import shutil
import os
for file in os.listdir(path):
if file.endswith(".jpg"):
src_dir = "your/source/dir"
dst_dir = "your/dest/dir"
shutil.move(src_dir,dst_dir)
Just use the following code
import shutil, os
files = ['file1.txt', 'file2.txt', 'file3.txt']
for f in files:
shutil.copy(f, 'dest_folder')
N.B.: You're in the current directory.
If You have a different directory, then add the path in the files list.
i.e:
files = ['/home/bucket/file1.txt', '/etc/bucket/file2.txt', '/var/bucket/file3.txt']
for jpgfile in glob.iglob(os.path.join(src_dir, "*", "*.jpg")):
shutil.copy(jpgfile, dst_dir)
You should write "**" before ".jpg" to search child directories. more "" means more subdirectory to search

match filenames to foldernames then move files

I have files named "a1.txt", "a2.txt", "a3.txt", "a4.txt", "a5.txt" and so on. Then I have folders named "a1_1998", "a2_1999", "a3_2000", "a4_2001", "a5_2002" and so on.
I would like to make the conection between file "a1.txt" & folder "a1_1998" for example. (I'm guessing I'll need a regular expresion to do this). then use shutil to move file "a1.txt" into folder "a1_1998", file "a2.txt" into folder "a2_1999" etc....
I've started like this but I'm stuck because of my lack of understanding of regular expresions.
import re
##list files and folders
r = re.compile('^a(?P')
m = r.match('a')
m.group('id')
##
##Move files to folders
I modified the answer below slightly to use shutil to move the files, did the trick!!
import shutil
import os
import glob
files = glob.glob(r'C:\Wam\*.txt')
for file in files:
# this will remove the .txt extension and keep the "aN"
first_part = file[7:-4]
# find the matching directory
dir = glob.glob(r'C:\Wam\%s_*/' % first_part)[0]
shutil.move(file, dir)
You do not need regular expressions for this.
How about something like this:
import glob
files = glob.glob('*.txt')
for file in files:
# this will remove the .txt extension and keep the "aN"
first_part = file[:-4]
# find the matching directory
dir = glob.glob('%s_*/' % first_part)[0]
os.rename(file, os.path.join(dir, file))
A slight alternative, taking into account Inbar Rose's suggestion.
import os
import glob
files = glob.glob('*.txt')
dirs = glob.glob('*_*')
for file in files:
filename = os.path.splitext(file)[0]
matchdir = next(x for x in dirs if filename == x.rsplit('_')[0])
os.rename(file, os.path.join(matchdir, file))

Categories