This question already has answers here:
open() gives FileNotFoundError / IOError: '[Errno 2] No such file or directory'
(8 answers)
Closed 6 months ago.
I have a small issue with a python program that I wrote to extract some information from a special text file. The loop (code below) needs to execute my function extract_zcoords() over 500 files (1 file gives one list) so that I can build a dataset.
import os
def extract_zcoord(filename):
f = open(filename, 'r')
... # do something with f
### LOOP OVER DIRECTORY
location = '/Users/spyros/Desktop/3NY8MODELSHUMAN/HomologyModels'
for filename in os.listdir(location):
extract_zcoord(filename)
THE ERROR:
The IOException No such file or directory is the one that occurs, so for some reason python is not accessing the files. I have checked directory pathname (location) and file permissions, and they are correct (read+write). Any ideas why an IOError would be reported when the files do exist and pathname is correct?
Any ideas what might be wrong?
Probably, you should use os.path.join when you call
zdata.extend(extract_zcoord(filename))
like this:
zdata.extend(extract_zcoord(os.path.join(location, filename)))
You need to join the dirname and filename into one complete path:
location = '/Users/spyros/Desktop/3NY8MODELSHUMAN/HomologyModels'
for filename in os.listdir(location):
filename = os.path.join(location, filename)
Related
This question already has answers here:
How to reliably open a file in the same directory as the currently running script
(9 answers)
Closed 2 years ago.
I am trying to open a file with python like this:
m = open("e.txt", 'r')
The text file I'm trying to open is in the same directory as my python file is.
However I'm getting an error message.
FileNotFoundError: [Errno 2] No such file or directory: 'e.txt'
I've also tried using:
import os
cwd = os.getcwd() # cwd: current working directory
path = os.path.join(cwd, "e.txt")
The error message looks a little different this time:
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\user\\e.txt'
I hope someone can help me with this issue. Thanks in advance.
The could be in a folder, if this is the case then the full name has to be written. Such as:
m = open("E://folder/e.txt","r")
print(m.read())
It is important to write the EXACT directory of the file.
The code is perfectly correct. Check the type of file whether it is .txt or some other file. If everything is correct you should check the location you gave
This question already has answers here:
Why does the 260 character path length limit exist in Windows?
(11 answers)
Closed 2 years ago.
I am trying to iteratively open some files to do some processing with the data. However, I haven't been able to make it work. I don't know what could be causing this.
sd = os.path.dirname(os.path.abspath(__file__))
file_names = []
for root,d_names,f_names in os.walk(os.path.join(sd, path)):
for f in f_names:
if f.endswith('.csv'):
file_names.append(os.path.join(root, f))
for f_name in file_names:
with open(f_name, 'r') as file:
...
I have also tried the following aproach, using pathlib
input_path = pathlib.Path(path)
file_names = input_path.glob('**/*.csv')
for f_name in file_names:
with open(f_name.resolve(), 'r') as file:
...
Both methods yield the same result.
'path' is the name of a directory that sits on the same directory as the script. Reading the error seems to indicate the path is correct. The files sit in a somewhat complex file structure with pretty long filenames at times.
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\...
To give a bit more insight, here is a brief simplified representation of the file structure of path
path
¦-dir1
¦¦-dir2
¦¦¦-dir3
¦¦¦¦-sub1
¦¦¦¦¦-file-1a
¦¦¦¦-sub2
¦¦¦¦¦-file-1b
¦¦¦¦¦-file-2b
What I've found by testing is that when I replace path by dir3 to remove uneccessary traversal, the script will process file-1a which is the only one in that directory and file-1b, but give the same error when reaching file-2b. Furthermore, when making sub2 the target instead, it will process all files inside sub2 with no issues.
Also, as suggested, I tried adding the line print(os.access(f_name, os.R_OK), repr(f_name)) just before attempting to open the file. It turns out it returns False every time just before the error is raised(followed by the file path), and returns True whenever I've managed to process a file.
Many thanks to #ekhumoro for pointing me in the right direction.
It seems my paths were longer than 260 characters, which is by default not allowed by Windows for backwards-compatibility reasons.
I changed the Windows registry to allow long paths and now my script has no issues accessing all the files in the structure.
This question already has answers here:
Python FTP get the most recent file by date
(5 answers)
Python FTP server download Latest File with specific keywords in filename
(1 answer)
Closed 4 years ago.
Good morning,
I'm trying to get the latest file in a folder stored in a ftp. That's why I created this function :
def getDataFromCSV_FTP(fileName, index_row_to_start):
"""
Create a data frame based on the csv named fileName and located on the FTP, starting to read at the index_row_to_start
"""
try :
list_of_files = ftp.nlst(fileName) # all files with following the path with csv format
latest_file = max(list_of_files, key=os.path.getctime)
df_from_csv = pd.read_csv(latest_file, skiprows=index_row_to_start, dtype="str")
return df_from_csv
except :
print ("Error while reading the file", fileName)
The function is able to find all files on the FTP (I got the list with all files) but I'm getting an issue when it executes the max(). It's telling me that the file doesn't exist (looks like it's looking on the local path) -> FileNotFoundError: [Errno 2] No such file or directory
I'm new with python and I'm missing something here
Please can someone help me to figure out what's going wrong ?
Thank you very much
This question already has answers here:
How to open every file in a folder
(8 answers)
Closed 2 years ago.
How can I read multiple txt file from a single folder in Python?
I tried with the following code but it is not working.
import glob
import errno
path = '/home/student/Desktop/thesis/ndtvnews/garbage'
files = glob.glob(path)
for name in files:
try:
with open(name) as f:
print name
for line in f:
print line,
f.close()
except IOError as exc:
if exc.errno != errno.EISDIR:
raise
Your glob isn't correct. You should add a /* to the end of your path to select all files (or directories) in your path, and then check if they are files with os.path.isfile. Something like:
from os.path import isfile
files=filter(isfile,glob.glob('%s/*'%path))
You also have an issue with the actual opening. When your with statement ends, the file is closed and f is no longer accessible. Anything you do with the file should be under the with statement. And you shouldn't explicitly close it.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
IOError when trying to open existing files
I'm having problems opening a file with open() in python 3.3, any idea why?
I'm trying
import os
filelist = [ f for f in os.listdir( os.curdir )]
singleFile = filelist[a]
hppfile = open(singleFile, 'r')
And I get
FileNotFoundError: [Errno 2] No such file or directory: '-file that is actually inside the directory-'
Ideas?
On Windows, I just started this to learn this to write few quick scripts
If you read the documentation for listdir you will see that it returns filenames and not full path.
You will need something like
current_dir_path = os.getcwd()
open(os.path.join(curren_dir_path, file), 'r')