File not found Python [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 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:
...

Related

os.path.exists() say False [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'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.

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(..)

Opening all files in a directory - Python [duplicate]

This question already has answers here:
How to identify whether a file is normal file or directory
(7 answers)
Closed 5 years ago.
I found some example code for ClamAV. And it works fine, but it only scans a single file. Here's the code:
import pyclamav
import os
tmpfile = '/home/user/test.txt'
f = open(tmpfile, 'rb')
infected, name = pyclamav.scanfile(tmpfile)
if infected:
print "File infected with %s Deleting file." %name
os.unlink(file)
else:
print "File is clean!"
I'm trying to scan an entire directory, here's my attempt:
import pyclamav
import os
directory = '/home/user/'
for filename in os.listdir(directory):
f = open(filename, 'rb')
infected, name = pyclamav.scanfile(filename)
if infected:
print "File infected with %s ... Deleting file." %name
os.unlink(filename)
else:
print " %s is clean!" %filename
However, I'm getting the following error:
Traceback (most recent call last):
File "anti.py", line 7, in <module>
f = open(filename, 'rb')
IOError: [Errno 21] Is a directory: 'Public'
I'm pretty new to Python, and I've read several similar questions and they do something like what I did, I think.
os.listdir("DIRECTORY") returns list of all files/dir in the DIRECTORY . It is just file names not absolute paths. So, if You are executing this program from a different directory it's bound to fail.
If you are sure that everything in the directory is a file, no sub directories. You can try following,
def get_abs_names(path):
for file_name in os.listdir(path):
yield os.path.join(path, file_name)
Then ,
for file_name in get_abs_names("/home/user/"):
#Your code goes here.
The following code will go over all your directory file by file. Your error happens because you try to open a directory as if it is a file instead of entering the dir and opening the files inside
for subdir, dirs, files in os.walk(path): # walks through whole directory
for file in files:
filepath = os.path.join(subdir, file) # path to the file
#your code here

Create a file in a directory using python

I am writing a python script in which I read a text file and I want to create a new text file in another directory.
I wrote the following code:
def treatFiles(oldFile, newFile):
with open(oldFile) as old, open(newFile, 'w') as new:
count = 0
for line in old:
count += 1
if count%2 == 0:
pass
else:
new.write(line)
if __name__ == '__main__':
from sys import argv
import os
os.makedirs('NewFiles')
new = '/NewFiles/' + argv[1]
treatFiles(argv[1], new)
I tried running this code with a text file in the same directory than my python script, but got an error like
FileNotFoundError: [Errno 2] No such file or directory: '/NewFiles/testFile'
Apparently, it is not clear that NewFiles is a directory in which it should create the new file... How can I correct this?
The problem is actually that in unix, /NewFiles/ means a folder in the root directory called NewFiles, not in the current directory. Remove the leading / and it should be fine.

Categories