"[Errno 2]" No such file or directory [duplicate] - python

This question already has answers here:
Trying to use open(filename, 'w' ) gives IOError: [Errno 2] No such file or directory if directory doesn't exist
(3 answers)
open() gives FileNotFoundError / IOError: '[Errno 2] No such file or directory'
(8 answers)
Closed 2 months ago.
This post was edited and submitted for review 2 months ago and failed to reopen the post:
Original close reason(s) were not resolved
Traceback (most recent call last):
File "c:\Users\*\Documents\GitHub\_Testes\novo_teste.py", line 1, in <module>
teste = open('teste.txt', 'w')
^^^^^^^^^^^^^^^^^^^^^^
FileNotFoundError: [Errno 2] No such file or directory: 'teste.txt'
I don't understand why it doesn't create the file and instead returns this error
I already tried 'w', 'w+', 'x', 'x+'. It simply only accepts if I use the absolute path, shouldn't it accept using the script directory as a base?
I tried using 'os.getcwd()':
import os
print(os.getcwd()) # Show the actual directory
arquivo = open(os.getcwd()+"\\teste.txt", "w")
arquivo.write('teste')
arquivo.close()
result:
PS C:\Users\*\Documents\GitHub\_Testes> & C:/Users/*/AppData/Local/Programs/Python/Python311/python.exe c:/_Projetos/_Testes/testes.py
C:\Users\*\Documents\GitHub\_Testes
Traceback (most recent call last):
File "c:\_Projetos\_Testes\testes.py", line 3, in <module>
arquivo = open(os.getcwd()+"\\teste.txt", "w")
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\*\\Documents\\GitHub\\_Testes\\teste.txt'

This is because from where you're calling (python novo_teste.py) it cannot find the file where you are (check if the path exist). You probably calling this from another directory.
If you want understanding or visualize the actual directory, do this:
import os
print(os.getcwd()) # Show the actual directory
print(os.listdir()) # Show all files and folder on it
file = open("teste.txt", "w")

Related

File not found error, but I did create a file, I think I had problem with coding

So the problem is, I create a fprak.txt on my desktop, and I tried to use the following code to open it, but Error comes out. I use jupyter
Code:
file=open('fprak.txt')
print(file)
Error:
FileNotFoundError Traceback (most recent call last)
<ipython-input-1-0d55e3a5adb7> in <module>
----> 1 file=open('fprak.txt')
2 print(file)
FileNotFoundError: [Errno 2] No such file or directory: 'fprak.txt'
Try using
file=open('~/Desktop/fprak.txt')
print(file)
Note that print(file) isn't going to print the file contents. Use print(file.read()) if you want to print the file contents.

Failing to make an array of Images in 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'

"FileNotFoundError: [Errno 2] No such file or directory" when trying to write to file [duplicate]

This question already has answers here:
os.makedirs doesn't understand "~" in my path
(3 answers)
Closed 6 months ago.
I am trying to save the image file got by requests.get()
def get_image_file(class_path,image_id):
r = requests.get(BASE_REQUEST_URL+'/image/'+image_id+'/download', stream=True)
print(r.url)
if r.status_code == 200:
with open(IMAGE_PATH+class_path+str(INCR)+'.jpg', 'wb+') as f:
r.raw.decode_content = True
shutil.copyfileobj(r.raw, f)
print("Image saved")
else:
print('Can not save the image.')
So, if image is benign, image will go to 'benign' folder.
When I call the function
get_image_file('benign/','5436e3acbae478396759f0d5')
Here what I get:
https://isic-archive.com/api/v1/image/5436e3acbae478396759f0d5/download
Traceback (most recent call last):
File "image_fetch.py", line 59, in <module>
get_image_file('benign/','5436e3acbae478396759f0d5')
File "image_fetch.py", line 34, in get_image_file
with open(IMAGE_PATH+class_path+str(INCR)+'.jpg', 'wb+') as f:
FileNotFoundError: [Errno 2] No such file or directory: '~/tf_files/benign/0.jpg'
I thought the problem is in the write permission.I tried to use 'wb','wb+','a+', but nothing helped.
~/tf_files isn't a valid path, unless you're working in a shell; the ~ gets expanded to your home directory by bash and co., not by the OS. If you want to have tildes in paths in Python, you should run them through os.path.expanduser before doing the open:
path = IMAGE_PATH+class_path+str(INCR)+'.jpg'
path = os.path.expanduser(path)
with open(path, 'wb+') as f:
# ...
pass

Creating text file: IOError: [Errno 21] Is a directory: '/Users/muitprogram/PycharmProjects/untitled/HR/train.txt'

I am trying to write to create and write to a text file. However, the error
Traceback (most recent call last):
File "/Users/muitprogram/PycharmProjects/untitled/histogramSet.py", line 207, in <module>
drinktrainfile = open(abs_file_path, "w")
IOError: [Errno 21] Is a directory: '/Users/muitprogram/PycharmProjects/untitled/HR/train.txt'
shows up. There are other instances of this in Stack Overflow, however, none of these deal with creating and writing a new file. The directories all exist however- only the file is being created The code that does this is:
import os
script_path = os.path.abspath(__file__) # i.e. /path/to/dir/foobar.py
script_dir = os.path.split(script_path)[0] # i.e. /path/to/dir/
rel_path = str(j) + "/train.txt" # HR/train.txt
abs_file_path = os.path.join(script_dir, rel_path) #/path/to/dir/HR/train.txt
drinktrainfile = open(abs_file_path, "w")
EDIT: train.txt shows up, except as a directory. How do I make it a text file?
The resource is actually a directory. It was very likely a mistake, as it is not likely that somebody would have created a directory by that name. First, remove that directory, and then try to create and open the file.
You can open the file with open('/Users/muitprogram/PycharmProjects/untitled/HR/train.txt', 'w'), assuming that the file does not already exist.

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

Categories