Loop over image filenames and split them - python

I'm trying to slice a bunch of images from a directory. Try to loop over them, but I'm getting FileNotFoundError: [Errno 2] No such file or directory: '45678.png'
Actually, that's the name of one of the files. This is my code:
import image_slicer
import os
indir = '/Users/data/h3'
for root, dirs, filenames in os.walk(indir):
for file in filenames:
if file.endswith('.png'):
image_slicer.slice(file, 4)
Dir is ok, I don't get why cannot find the file, when actually finds it as per the error message

You need to add the path to the filename when you open it with slice().
Try image_slicer.slice(os.path.join(dirpath, name), 4)

Related

Move files from subfolders to another folder

I want to move all the files from multiple subdirectories to another folder in the same directory as the parent folder but get the following error:
FileNotFoundError: [Errno 2] No such file or directory: '/content/drive/MyDrive/Dev/FaceRec/lfw/Emmit_Smith/Emmit_Smith_0001.jpg' -> '/content/drive/MyDrive/Dev/FaceRec/negatives/Emmit_Smith_0001.jpg'
this is my code:
for directory in os.listdir('/content/drive/MyDrive/Dev/FaceRec/lfw'):
for file in os.listdir(os.path.join('/content/drive/MyDrive/Dev/FaceRec/lfw', directory)):
path = os.path.join('/content/drive/MyDrive/Dev/FaceRec/lfw', directory, file)
new_path = os.path.join('/content/drive/MyDrive/Dev/FaceRec/negatives', file)
os.replace(path, new_path)
Thank you for the help in advance
Try the following:
import os
import glob
import shutil
src_path = '/content/drive/MyDrive/Dev/FaceRec/lfw'
dest_path = src_path.replace('lfw', 'negatives')
flist = glob.glob(os.path.join(src_path, '*/*'))
for fname in flist:
shutil.move(fname, fname.replace(os.path.dirname(fname), dest_path))
Why this is better:
The glob functions helps to avoid one for loop and also prevents from repeatedly joining the paths together
shutil.movecreates the destination directory for you if it does not exist. Also it can handle symlinks.
By putting the paths in variables we can minimize copy past errors

Rename: FileNotFoundError: [WinError 2] - working with rasters

In my code in Python I keep getting the error
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'Z_Cawc_000_005_estimated_value.tfw' -> 'awc_000_005_estimated_value.tfw'
So,
'Z_Cawc_000_005_estimated_value.tfw' is the name of the first raster on a folder with 800 rasters.
All I want is to get rid off the initial "Z_C" characters of the 800 raster files in a folder.
My code is
import os
path = os.getcwd()
filenames =
os.listdir(r'I:\PhD_2019\Spatial_Datasets\Baroon_Pocket_Dam_Catchment\Raster\Soil_Zonal_Stats')
for filename in filenames:
os.rename(filename, filename.replace("Z_C",""))
I`ve also try the following code:
from os import rename, listdir
badprefix = "Z_C"
fnames = listdir('I:\\PhD_2019\\Spatial_Datasets\\Baroon_Pocket_Dam_Catchment\\Raster\\Soil_Zonal_Stats')
for fname in fnames:
if fname.startswith(badprefix):
rename(fname, fname.replace(badprefix, '', 1))
and the following code as well:
import os
path = os.getcwd()
filenames = os.listdir(r'I:\PhD_2019\Spatial_Datasets\Baroon_Pocket_Dam_Catchment\Raster\Soil_Zonal_Stats' )
for filename in filenames:
os.rename(filename, filename.replace("Z_C", ""))
But both of them resulted in the same error!
Can anyone let me know what is wrong with my code, please?
You need to specify the full path to the file, otherwise python would look in your working directory and won't find the file. the fix is:
folder = r'I:\PhD_2019\Spatial_Datasets\Baroon_Pocket_Dam_Catchment\Raster\Soil_Zonal_Stats'
filenames =
os.listdir(r'I:\PhD_2019\Spatial_Datasets\Baroon_Pocket_Dam_Catchment\Raster\Soil_Zonal_Stats')
for filename in filenames:
os.rename(os.path.join(folder, filename), os.path.join(folder, filename.replace("Z_C","")))

Can't delete files - getting FileNotFoundError

I am trying to write a program that will delete files inside a specific folder.
When I run the following code, I get the error:
FileNotFoundError: [Errno 2] No such file or directory: '/Users/joshuamorse/Documents/Programming/python/deletefiles/1.txt
My code:
import os, sys
for filename in os.listdir('/Users/joshuamorse/Documents/programming/python/deletefiles/f2d/'):
print(filename)
x = os.path.realpath(filename) #not required but included so program would give more meaningful error
os.unlink(x)
when line 5 is commented out the program runs fine and lists all the files contained in the folder.
I do not understand why the error is cutting off the last folder (f2d) in the directory path. Additionally if I miss type the last folder in the path to something like f2 it produces the following error: FileNotFoundError: [Errno 2] No such file or directory: '/Users/joshuamorse/Documents/programming/python/deletefiles/f2/.
Why is the last folder included in the path only when it is mispelled? How would I go about fixing this so the correct path is passed?
Solution
Provided by #ekhumoro
os.listdir() does not return the path, just the files names in the specified folder.
Corrected Code
import os
dirpath = '/Users/joshuamorse/Documents/programming/python/deletefiles/f2d/'
for filename in os.listdir(dirpath):
x = os.path.join(dirpath, filename)
os.unlink(x)

Unable to open file located inside subdirectory python

I want to read data from specific files from a directory whose structure is as follows:
-Directory
-Subdirectory1
-AGreek.srt
-AEnglish.srt
-Subdirectory2
-BGreek.srt
-BEnglish.srt
-test.py
Where test.py is my script and I'm supposed to read only the english files from the Directory. This is my current script:
import os
substring = 'English.srt'
for root, subdirs, files in os.walk('Directory'):
for filename in files:
if substring in filename:
fp = open(os.path.abspath(filename))
# Further Action
However this is giving me the following error:
FileNotFoundError: [Errno 2] No such file or directory: '/home/coder/Spam/AEnglish.srt'
How do I resolve the error? (P.s.: Spam is the folder inside which Directory and test.py are located)
You need to use os.path.join(root,filename) to access the file.
Ex:
import os
substring = 'English.srt'
for root, subdirs, files in os.walk('Directory'):
for filename in files:
if substring in filename:
fp = open(os.path.join(root,filename))
# Further Action

WindowsError: [Error 267] The directory name is invalid - Spyder 2.7

I am trying to print the file names in my directory using the following code:
dir_path = 'D:/#/#/#/#.json'
for filename in os.listdir(dir_path):
print filename
f = open(os.path.join(dir_path,filename), 'r')
but this error is displayed when running the code:
for filename in os.listdir(dir_path):
WindowsError: [Error 267] The directory name is invalid: 'D:/#/#/#/#.json/*.*'
I am unsure what the json/*.* means in the error message, I am new to Python so apologies if this question is vague.
Your question is unclear as to whether the directory D:/#/#/# contains any files in it other than JSON files, so I shall give two answers. Hopefully one of them will apply to you:
Directory contains only JSON files
In that case, simply remove the /#.json from the end of dir_path:
dir_path = 'D:/#/#/#'
for filename in os.listdir(dir_path):
print filename
f = open(os.path.join(dir_path,filename), 'r')
Directory contains JSON files and other files that you want to exclude
In this situation it's best to use the Python glob module.
The following should list all of the .json files in the folder D:/#/#/#:
import glob
dir_path = 'D:/#/#/#/*.json'
for filename in glob.glob(dir_path):
print filename
f = open(filename, 'r')
Note that filenames returned by glob.glob include the directory path, so we don't use os.path.join on them.
os.listdir lists all files in the directory you give it. However it seems you're not passing it the name of a directory, you're passing it the name of a file. How can it possibly list all the files in a directory if you don't give it a directory?

Categories