os.path.exists() say False [duplicate] - python

This question already has answers here:
open() gives FileNotFoundError / IOError: '[Errno 2] No such file or directory'
(8 answers)
Closed 7 months ago.
I'm trying to make a code that downloads a file if it doesn't exist
import requests
from os.path import exists
def downloadfile(url):
if exists('file.txt')==False:
local_filename = url.split('/')[-1]
with requests.get(url, stream=True) as r:
r.raise_for_status()
with open(local_filename, 'wb') as f:
for chunk in r.iter_content(chunk_size=8192):
f.write(chunk)
return
downloadfile('https://url.to/file.txt')
my folder:
testfolder
test.py
file.txt
...
in idle
from os.path import exists
exists('file.txt') # True
in test.py, exists() say False
how fix it?

If it reads false, it's probably looking in the wrong place. Use the following to see where the code is looking in (file directory):
import os
print(os.getcwd())
Then you can either put the file you're looking for in that directory or change the code to the file directory which the file is currently in.

Related

Python: File Not Found Error. No such file or directory named [duplicate]

This question already has answers here:
Why am I getting a FileNotFoundError? [duplicate]
(8 answers)
Closed 9 months ago.
I have to read a simple file named 'highscore.txt' in my slakes.py file.
Both are located in same folder.
But idk why I am getting file not found error
Code:
with open('highscore.txt', 'r') as f:
high_score = f.read()
This part of code check if file is exist. If not - create this empty file and read this file.
I recommend using the full path to your file like /home/user/folde/subfolder/file.txt
I hope this helps you.
from subprocess import call as subprocess_call
from os.path import isfile as file_exist
file = "/path/to/your/file"
if not file_exist(file):
# create file if exist
subprocess_call(["touch", file])
subprocess_call(["chmod", "777", file])
with open(file, "r") as f:
high_score = f.read()
Try using module named csv
The following code is a basic code to read a file:
import csv
with open('file directory') as F:
reader = csc.reader(F)
for row in reader:
print (rows)
You can use any variables
Please check whether the folder where the VS Code terminal is currently located is the parent folder of the python file being executed.
Solution:
You could use the command "cd folder_name" in the terminal to go to the parent folder of the python file:
Or use the following settings in the settings file "settings.json":
"python.terminal.executeInFileDir": true,
It will automatically go to the parent folder of the current file before executing the run command:

File not found Python [duplicate]

This question already has answers here:
open() gives FileNotFoundError / IOError: '[Errno 2] No such file or directory'
(8 answers)
Closed 7 months ago.
I have tried to get my program to open but it keeps saying FileNotFound
def main():
with open("number.txt") as f:
nums=[int(x) for x in f.read().split()]
print(nums)
for nums in nums:
total += int(nums)
print(total)
print(len(nums))
return total / len(nums)
main()
Is number.txt in your working directory? If not you'd have to specify the path to that file so python knows where to look
Python will look for "number.txt" in your current directory which by default is the same folder that your code started running in. You can get the current directory by using os.getcwd() and if that for some reason is not what you expect, you can also get the directory to the folder that your code is running in by doing current_directory = os.path.dirname(os.path.realpath(__file__)).
The following code should always work, if you want your "number.txt" to be in the same folder as your code.
import os.path
def main():
current_directory = os.path.dirname(os.path.realpath(__file__))
filepath = os.path.join(current_directory, "number.txt")
# Optionally use this to create the file if it does not exist
if not os.path.exists(filepath):
open(filepath, 'w').close()
with open( filepath ) as f:
...

How can I check if a file exists in python? [duplicate]

This question already has answers here:
How do I check whether a file exists without exceptions?
(40 answers)
Closed 3 years ago.
I am trying to make a python script to make entries in an excel file that will have daily entries.
I want to check if a file exists then open it.
if the file does not exist then I want to make a new file.
if have used os path exists to see if the file is present
workbook_status = os.path.exists("/log/"+workbookname+".xlxs")
if workbook_status = "True":
# i want to open the file
Else:
#i want to create a new file
I think you just need that
try:
f = open('myfile.xlxs')
f.close()
except FileNotFoundError:
print('File does not exist')
If you want to check with if-else than go for this:
from pathlib import Path
my_file = Path("/path/to/file")
if my_file.is_file():
# file exists
import os
import os.path
PATH='./file.txt'
if os.path.isfile(PATH) and os.access(PATH, os.R_OK):
print "File exists and is readable/there"
else:
f = open('myfile.txt')
f.close()
You should use following statement:
if os.path.isfile("/{file}.{ext}".format(file=workbookname, ext=xlxs)):
# Open file

Open all json files in a folder [duplicate]

This question already has answers here:
Python: Read several json files from a folder
(9 answers)
Closed 4 years ago.
I have a folder with hundreds of .json files.
How to open all these files at once?
I have tried:
for i in os.listdir('C:/Users/new'):
if i.endswith('.json'):
files.append(open(i).read)
But I got this error:
FileNotFoundError: [Errno 2] No such file or directory:
i is only the filename. you should give the full path to the program.
example: let first file be stackoverflow.json
you try to open with filename such as:
open('stackoverflow.json', 'r')
what you should do is:
open('C:/Users/new/stackoverflow.json', 'r')
so the code should do it:
files = []
base_path = 'C:/Users/new'
for i in os.listdir(base_path):
if i.endswith('.json'):
full_path = '%s/%s' % (base_path, i)
files.append(open(full_path, 'r', encoding='utf-8').read())
print("starting to print json documents...")
for single_file in files:
print(single_file)
print("printing done")
EDIT: as #khelwood states, you should also replace read with read().

IOError: [Errno 2] No such file or directory (when it really exist) Python [duplicate]

This question already has answers here:
IOError: [Errno 2] No such file or directory Python
(1 answer)
Python on Windows: IOError: [Errno 2] No such file or directory
(2 answers)
IOError: [Errno 2] No such file or directory trying to open a file [duplicate]
(5 answers)
Closed 5 years ago.
I'm working on transfer folder of files via uart in python. Below you see simple function, but there is a problem because I get error like in title : IOError: [Errno 2] No such file or directory: '1.jpg' where 1.jpg is one of the files in test folder. So it is quite strange because program know file name which for it doesn't exist ?! What I'm doing wrong ?
def send2():
path = '/home/pi/Downloads/test/'
arr = os.listdir(path)
for x in arr:
with open(x, 'rb') as fh:
while True:
# send in 1024byte parts
chunk = fh.read(1024)
if not chunk: break
ser.write(chunk)
You need to provide the actual full path of the files you want to open if they are not in your working directory :
import os
def send2():
path = '/home/pi/Downloads/test/'
arr = os.listdir(path)
for x in arr:
xpath = os.path.join(path,x)
with open(xpath, 'rb') as fh:
while True:
# send in 1024byte parts
chunk = fh.read(1024)
if not chunk: break
ser.write(chunk)
os.listdir() just returns bare filenames, not fully qualified paths. These files (probably?) aren't in your current working directory, so the error message is correct -- the files don't exist in the place you're looking for them.
Simple fix:
for x in arr:
with open(os.path.join(path, x), 'rb') as fh:
…
Yes, code raise Error because file which you are opening is not present at current location from where python code is running.
os.listdir(path) returns list of names of files and folders from given location, not full path.
use os.path.join() to create full path in for loop.
e.g.
file_path = os.path.join(path, x)
with open(file_path, 'rb') as fh:
.....
Documentation:
os.listdir(..)
os.path.join(..)

Categories