Unable to open or read log files: FileNotFoundError [duplicate] - python

I'm trying to run the following script which simply reads and image and saves it again:
from PIL import Image
import os
rootdir = '/home/user/Desktop/sample'
for subdir, dirs, files in os.walk(rootdir):
for file in files:
im = Image.open(file)
im.save(file)
I however get the following error:
Traceback (most recent call last):
File "test.py", line 10, in <module>
im = Image.open(file)
File "/usr/lib/python2.7/dist-packages/PIL/Image.py", line 2258, in open
fp = builtins.open(filename, "rb")
IOError: [Errno 2] No such file or directory: '1.jpg'
So, what I'm trying to do is simply read the file 1.jpg and save it again, provided that 1.jpg is located in the directory.
How can I fix this issue?
Thanks.

You're going to need to provide a fully qualified path, because file holds only the tail, not the entire path.
You can use os.path.join to join the root to the tail:
for root, dirs, files in os.walk(rootdir):
for file in files:
path = os.path.join(root, file)
im = Image.open(path)
im.save(path)

Related

Why does do I have an IO error saying my file doesn't exist even though it does exist in the directory?

I am trying to loop over a Python directory, and I have a specific file that happens to be the last file in the directory such that I get an IOerror for that specific file.
The error I get is:
IOError: [Errno 2] No such file or directory: 'nod_gyro_instance_11_P_4.csv'
My script:
for filename in os.listdir("/Users/my_name/PycharmProjects/My_Project/Data/Nod/Gyro"):
data = []
if filename.endswith(".csv"):
data.append(k_fold(filename))
continue
else:
continue
k_fold does this:
def k_fold(myfile, myseed=11109, k=20):
# Load data
data = open(myfile).readlines()
The entire traceback:
Traceback (most recent call last):
File "/Users/my_name/PycharmProjects/MY_Project/Cross_validation.py", line 30, in <module>
data.append(k_fold(filename))
File "/Users/my_name/PycharmProjects/My_Project/Cross_validation.py", line 8, in k_fold
data = open(myfile).readlines()
IOError: [Errno 2] No such file or directory: 'nod_gyro_instance_11_P_4.csv'
My CSV files are such:
nod_gyro_instance_0_P_4.csv
nod_gyro_instance_0_P_3.csv
nod_gyro_instance_0_P_2.csv
nod_gyro_instance_0_P_5.csv
...
nod_gyro_instance_11_P_4.csv
nod_gyro_instance_10_P_6.csv
nod_gyro_instance_10_P_5.csv
nod_gyro_instance_10_P_4.csv
Why doesn't it recognize my nod_gyro_instance_10_P_4.csv file?
os.listdir returns just filenames, not absolute paths. If you're not currently in that same directory, trying to read the file will fail.
You need to join the dirname onto the filename returned:
data_dir = "/Users/my_name/PycharmProjects/My_Project/Data/Nod/Gyro"
for filename in os.listdir(data_dir):
k_fold(os.path.join(data_dir, filename))
Alternatively, you could use glob to do both the listing (with full paths) and extension filtering:
import glob
for filename in glob.glob("/Users/my_name/PycharmProjects/My_Project/Data/Nod/Gyro/*.csv"):
k_fold(filename)

Renaming all the files in folders within directory

Basically I have got it all done. But when actually trying to rename the files I get the error
Traceback (most recent call last):
File
"C:\Users\CHOMAN\Desktop\Earthquake_1_combine_3_jan\Earthquake_1_combine\wav\sort_inner_wav.py", line 21, in <module>
os.rename(file, new_name)
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'Audio Track-10.wav' -> 'choman_10.wav'
Up until the last print statement the values are correct. Not sure how to rename it. Under wav folder there are 32 sub folder which has around 10 .wav files in it.
import os
rootdir = r'C:\Users\CHOMAN\Desktop\Earthquake_1_combine_3_jan\Earthquake_1_combine\wav'
for subdir, dirs, files in os.walk(rootdir):
for file in files:
filepath = subdir+os.sep+file
if filepath.endswith('.wav'):
f_name, f_ext=(os.path.splitext(file))
if len(f_name) == 11:
f_name = f_name+'-0'
f_title,f_num =f_name.split('-')
f_num=f_num.zfill(2)
new_name = '{}_{}{}'.format('choman',f_num,f_ext)
print (file, new_name)
os.rename(file, new_name)
All you need is:
os.rename(filepath, subdir+os.sep+new_name)
That's because you need the full path.
If you are not running this script under the same location as 'rootdir' and there are sub directories, you need to specify the absolute path of source file and destination file. Otherwise, the file would not be found.
# python 2.7
os.rename(filepath, os.path.join(subdir, new_name))
# python >= 3.3
os.rename(file, new_name, subdir, subdir)

fp = builtins.open(filename, "rb") - Error

When I try running this script:
from PIL import Image
import os
files = os.listdir('mri')
for file in files:
img = Image.open(file)
I get the following error:
Traceback (most recent call last):
File "resize_image.py", line 6, in <module>
img = Image.open(file)
File "/usr/lib/python2.7/dist-packages/PIL/Image.py", line 2258, in open
fp = builtins.open(filename, "rb")
IOError: [Errno 2] No such file or directory: '6.jpg'
I made sure that 6.jpg is available. And, it seems that I get such error for any image in this location.
How can I fix the issue?
Thanks.
The file names from os.listdir are relative to the directory given. They must be made complete by joining the dirname to their basename.
files = os.listdir('my_folder')
for file in files:
img = Image.open(os.path.join('my_folder', file))
You are getting this error because you haven't add your image in project file folder.
Paste your image in project file and then run the program.
img = Image.open(os.path.join('mri', file))
this worked for me making sure you join the dir with the path
img = Image.open(os.path.join(r'C:\Users\Simin\Desktop\python proj\img.jpg'))
this direct path worked for me

Python zipfile crashes gives an error for some files

I have a simple code to zip files using zipfile module. I am able to zip some files but I get FileNotFound error for the others. I have checked if this is file size error but its not.
I can pack files with name like example file.py but when I have a file inside a directory like 'Analyze Files en-US_es-ES.xlsx' if fails.
It works when I change os.path.basename to os.path.join but I don't want to zip whole folder structure, I want to have flat structure in my zip.
Here is my code:
import os
import zipfile
path = input()
x=zipfile.ZipFile('new.zip', 'w')
for root, dir, files in os.walk(path):
for eachFile in files:
x.write(os.path.basename(eachFile))
x.close()
Error looks like this:
Traceback (most recent call last):
File "C:/Users/mypc/Desktop/Zip test.py", line 15, in <module>
x.write(os.path.basename(eachFile))
File "C:\Python34\lib\zipfile.py", line 1326, in write
st = os.stat(filename)
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'Analyze Files en-US_ar-SA.xlsx'*
Simply change working directory to add file without original directory structure.
import os
import zipfile
path = input()
baseDir = os.getcwd()
with zipfile.ZipFile('new.zip', 'w') as z:
for root, dir, files in os.walk(path):
os.chdir(root)
for eachFile in files:
z.write(eachFile)
os.chdir(baseDir)

Trouble moving files from folder to folder python

I am having trouble moving files from one folder to another. I have written this simple code:
import os
import shutil
movePath = "C:\\Users\\BWhitehouse\\Documents\\GVRD\\MonthlySummary_03\\SCADA"
destPath = "I:\\eng\\GVRD\\Rain_Gauges\\MonthlyDownloads\\2014-03"
for dirpath, dirs, files in os.walk(movePath):
for file in files:
if file.endswith('.xls'):
shutil.copy(file, destPath)
And this is the error I am getting:
Traceback (most recent call last):
File "C:\Python34\test.py", line 12, in <module> shutil.copy(file, destPath)
File "C:\Python34\lib\shutil.py", line 228, in copy copyfile(src, dst, follow_symlinks=follow_symlinks)
File "C:\Python34\lib\shutil.py", line 107, in copyfile with open(src, 'rb') as fsrc:
FileNotFoundError: [Errno 2] No such file or directory: 'BU07-201403.xls'
If anyone could help me out that would be greatly appreciated!
The file variable is just the name, to get the full path add it to the dirpath variable:
shutil.copy( os.path.join(dirpath, file), destPath )
Do you have full access to these folders? First check it out.
Start Python as Administrator by right-clicking, when you try to start the script.
I had the same problem. I solved the problem in this way.

Categories

Resources