Failing to make an array of Images in Python - python

I am trying to create an array of .jpg files, but the compiler is not building the array
More specifically, my problem is that a public folder, whose path is defined as the object path, is not accessible by my Python compiler [Spyder]. However, the folder, and its respective files are all public and open access to everyone. What might be the reason that my computer cannot access the images?
Code 1 is an simple function to find and access the file path I want, and the Kernal results show what is failing.
Code 2 is the syntax for the isolated error in the program I am applying the open() method. Kernal results depict compiler failure.
Code 1:
import os
path = r'C:/Users/BeckerLab/Pictures/Final_Sample_Set/Right2'
try:
os.path.exists(path)
if (True):
R = open(path)
R.close()
except FileNotFoundError:
print("file does not exist")
Kernal for Code 1:
!runfile('C:/Users/BeckerLab/untitled6.py', wdir='C:/Users/BeckerLab')
Traceback (most recent call last):
File "C:\Users\BeckerLab\untitled6.py", line 8, in <module>
R = open(path)
PermissionError: [Errno 13] Permission denied: 'C:/Users/BeckerLab/Pictures/Final_Sample_Set/Right2'
Code 2:
import os
rightSamples = [open(file, 'r+') for file in os.listdir(r'C:/Users/Public/Right2')]
Kernal Results for Code 2:
!runfile('C:/Users/BeckerLab/almost.py', wdir='C:/Users/BeckerLab')
2020-04-05 12:59:28
Traceback (most recent call last):
File "C:\Users\BeckerLab\almost.py", line 46, in <module>
rightSamples = [open(file, 'r+') for file in os.listdir(r'C:/Users/Public/Right2')]
File "C:\Users\BeckerLab\almost.py", line 46, in <listcomp>
rightSamples = [open(file, 'r+') for file in os.listdir(r'C:/Users/Public/Right2')]
FileNotFoundError: [Errno 2] No such file or directory: 'R1.JPG'

Notice that your condition is:
os.path.exists(path)
if (True):
which will always be true. Maybe try:
if (os.path.exists(path)):
Try moving the files to another directory like 'D:/../BeckerLab/untitled6.py'

Related

FileNotFoundError when sorting files by size

I am trying create a list of image file names, sorted by the size of the file:
path = '/home/onur/Desktop/dataset/'
images = sorted(os.listdir(path), key = os.path.getsize)
print(images)
But I'm getting this error:
Traceback (most recent call last):
File "/home/onur/Desktop/image-downloader.py", line 98, in <module>
images = sorted(os.listdir(path), key = os.path.getsize)
File "/usr/lib/python3.9/genericpath.py", line 50, in getsize
return os.stat(filename).st_size
FileNotFoundError: [Errno 2] No such file or directory: 'image_535.jpg'
The python file is NOT in /home/onur/Desktop/dataset/. It is just in Desktop so I wonder if that is the reason for the error. If so, how can I fix it?
You are correct. The problem is that os.path.getsize raises an error if the file does not exist. Because your Python script is in /home/onur/Desktop and the file name passed to os.path.getsize is just image_535.jpg, os.path.getsize looks for the file in your Desktop directory. Since the file is not there, os.path.getsize raises the error. You could run this to correctly test the file size.
path = '/home/onur/Desktop/dataset/'
images = sorted(os.listdir(path), key=lambda f: os.path.getsize(os.path.join(path, f)))
print(images)

PermissionError: [Errno 13] Permission denied - Python cannot write/open/read any text or image files

This stuff was ok until recently and I've searched everywhere.
I'm trying to get an image from the internet and then download it.
I'm using python on Windows installed via Anaconda. THe same error occurs on powershell as well as anaconda prompt.
My code (test.py):
from PIL import Image
import requests
from io import BytesIO
import cv2
import numpy
img_url = 'https://d.newsweek.com/en/full/520858/supermoon-moon-smartphone-photo-picture.jpg'
response = requests.get(img_url)
img = Image.open(BytesIO(response.content))
uid = 1
fname = 'test'
x_start, y_start, x_end, y_end = 0,0,10,10
crp = img.crop((x_start, y_start, x_end, y_end))
crp.save('test.jpg')
The error (when running python test.py in console):
Traceback (most recent call last):
File ".\imgtest.py", line 16, in <module>
crp.save('test.jpg')
File "C:\ProgramData\Anaconda3\lib\site-packages\PIL\Image.py", line 2148, in save
fp = builtins.open(filename, "w+b")
PermissionError: [Errno 13] Permission denied: 'test.jpg'
Things I've tried
Changing permissions of the folder that the file is in
Running command prompt as administrator
Tested creating a text file as well using f = open("demo.txt", "w"). The error this time is:
Traceback (most recent call last):
File ".\imgtest.py", line 15, in
f = open("demo.txt", "w")
PermissionError: [Errno 13] Permission denied: 'demo.txt'
From the documentation, try to pass the format as a param:
crp.save('test', "jpg")
or
crp.save('test', "JPEG")
Also from the documentation, Your IOError Raise when:
the file could not be written. The file may have been created and may contain partial data.

Downloading a file but getting permission errors

I'm trying to download a file but when it's trying to write to the current directory it gives a permission error
Traceback (most recent call last):
File "C:\Users\HP User\Desktop\WWE Tool\MasterDownload.py", line 22, in <module>
with open(x, 'wb') as f:
PermissionError: [Errno 13] Permission denied: 'C:\\Users\\HP User\\Desktop\\WWE Tool'
Code:
MasterDownload = requests.get(url=Master, headers=Heads)
fpath = os.getcwd()
with open(fpath, 'wb') as f:
f.write(MasterDownload.content)
I checked the current path and eveything looks fine, I just can't get around as to why it's not writing as I am an admin
You're actually trying to write to a directory (the process' current working directory - as obtained from os.getcwd()), not to a file. Try selecting an actual file in that directory to write to instead of the directory itself, and the issue might go away.

How do I change/choose the file path in Python?

I'm trying to access a .txt file in Python and I can't figure out how to open the file. I ended up copying the contents into a list directly but I would like to know how to open a file for the future.
If I run this nothing prints. I think it's because Python is looking in the wrong folder/directory but I don't know how to change file paths.
sourcefile = open("CompletedDirectory.txt").read()
print(sourcefile)
The file CompletedDirectory.txt is probably empty.
If Python could not find the file, you would get a FileNotFoundError exception:
>>> sourcefile = open("CompletedDirectory.txt").read()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
FileNotFoundError: [Errno 2] No such file or directory: 'CompletedDirectory.txt'
Note that using read() in this way is not recommended. You're not closing the file properly. Use a context manager:
with open("CompletedDirectory.txt") as infile:
sourcefile = infile.read()
This will automatically close infile on leaving the with block.
You can get the current working directory:
import os
os.getcwd()
Then just concat it with the file container directory
os.path.join("targetDir", "fileName")

root directory IOError: [Errno 13] Permission denied:

I am working on Ubuntu and writing a code in python. I want to add a line in a file which is placed in root directory:
ins = open( "/usr/local/etc/conf.d/test.txt", "r" )
array = []
for line in ins:
array.append( line )
array.append('add this new line')
f = open("/usr/local/etc/gnuradio/test.txt",'w')
for line in array:
f.write(line)
I am getting this error:
Traceback (most recent call last):
File "overwrite.py", line 6, in <module>
f = open("/usr/local/etc/gnuradio/test.txt",'w')
IOError: [Errno 13] Permission denied: '/usr/local/etc/gnuradio/test.txt'
I know we do not have permission to change anything in root directory without using sudo. But is there anyway I can update this file from within my python module?
You already answered your own question: You do not have the permission to do so.
No matter if you use sh, bash, python, C, erlang or a rubber-hose attack.
Either run your script with a user owning the necessary permissions or grant yourself access to the file.

Categories