Probably a very noob question..
But
When I try:
f = open(os.path.join(os.path.dirname(__file__), filename),"w")
I get an error
IOError: [Errno 2] No such file or directory: '/home/path/filename'
Isnt it that since i have said "w" .. it will write a new file if its not there already?
The error message can be reproduced like this:
import os
filename = '/home/path/filename'
f = open(os.path.join(os.path.dirname(__file__), filename),"w")
f.close()
# IOError: [Errno 2] No such file or directory: '/home/path/filename'
The problem here is that filename is an absolute path, so
os.path.join ignores the first argument and returns filename:
In [20]: filename = '/home/path/filename'
In [21]: os.path.join(os.path.dirname(__file__), filename)
Out[21]: '/home/path/filename'
Thus, you are specifying not only a file that does not exist, you are specifying a directory that does not exist. open refuses to create the directory.
Are you trying to literally write home/path/filename? In that case, it's complaining that /home/path doesn't exist. Try creating a directory named /home/path or choosing a file name inside a directory that already exists (for example, find out what the path is to your actual home directory.) You can also use relative paths. See
http://en.wikipedia.org/wiki/Path_%28computing%29
for the difference between absolute and relative paths.
Related
I am trying to write a program that will delete files inside a specific folder.
When I run the following code, I get the error:
FileNotFoundError: [Errno 2] No such file or directory: '/Users/joshuamorse/Documents/Programming/python/deletefiles/1.txt
My code:
import os, sys
for filename in os.listdir('/Users/joshuamorse/Documents/programming/python/deletefiles/f2d/'):
print(filename)
x = os.path.realpath(filename) #not required but included so program would give more meaningful error
os.unlink(x)
when line 5 is commented out the program runs fine and lists all the files contained in the folder.
I do not understand why the error is cutting off the last folder (f2d) in the directory path. Additionally if I miss type the last folder in the path to something like f2 it produces the following error: FileNotFoundError: [Errno 2] No such file or directory: '/Users/joshuamorse/Documents/programming/python/deletefiles/f2/.
Why is the last folder included in the path only when it is mispelled? How would I go about fixing this so the correct path is passed?
Solution
Provided by #ekhumoro
os.listdir() does not return the path, just the files names in the specified folder.
Corrected Code
import os
dirpath = '/Users/joshuamorse/Documents/programming/python/deletefiles/f2d/'
for filename in os.listdir(dirpath):
x = os.path.join(dirpath, filename)
os.unlink(x)
I am trying to open the file from folder and read it but it's not locating it. I am using Python3
Here is my code:
import os
import glob
prefix_path = "C:/Users/mpotd/Documents/GitHub/Python-Sample-
codes/Mayur_Python_code/Question/wx_data/"
target_path = open('MissingPrcpData.txt', 'w')
file_array = [os.path.abspath(f) for f in os.listdir(prefix_path) if
f.endswith('.txt')]
file_array.sort() # file is sorted list
for f_obj in range(len(file_array)):
file = os.path.abspath(file_array[f_obj])
join_file = os.path.join(prefix_path, file) #whole file path
for filename in file_array:
log = open(filename, 'r')#<---- Error is here
Error: FileNotFoundError: [Errno 2] No such file or directory: 'USC00110072.txt'
You are not giving the full path to a file to the open(), just its name - a relative path.
Non-absolute paths specify locations in relation to current working directory (CWD, see os.getcwd).
You would have to either os.path.join() correct directory path to it, or os.chdir() to the directory that the files reside in.
Also, remember that os.path.abspath() can't deduce the full path to a file just by it's name. It will only prefix its input with the path of the current working directory, if the given path is relative.
Looks like you are forgetting to modify the the file_array list. To fix this, change the first loop to this:
file_array = [os.path.join(prefix_path, name) for name in file_array]
Let me reiterate.
This line in your code:
file_array = [os.path.abspath(f) for f in os.listdir(prefix_path) if f.endswith('.txt')]
is wrong. It will not give you a list with correct absolute paths. What you should've done is:
import os
import glob
prefix_path = ("C:/Users/mpotd/Documents/GitHub/Python-Sample-"
"codes/Mayur_Python_code/Question/wx_data/")
target_path = open('MissingPrcpData.txt', 'w')
file_array = [f for f in os.listdir(prefix_path) if f.endswith('.txt')]
file_array.sort() # file is sorted list
file_array = [os.path.join(prefix_path, name) for name in file_array]
for filename in file_array:
log = open(filename, 'r')
You are using relative path where you should be using an absolute one. It's a good idea to use os.path to work with file paths. Easy fix for your code is:
prefix = os.path.abspath(prefix_path)
file_list = [os.path.join(prefix, f) for f in os.listdir(prefix) if f.endswith('.txt')]
Note that there are some other issues with your code:
In python you can do for thing in things. You did for thing in range(len(things)) it's much less readable and unnecessary.
You should use context managers when you open a file. Read more here.
So I have been trying to write a text file in a specific directory with the following code (note_value and note_title are variables already set to a string) :
file = open("resources/user_notes/" + note_title + ".txt", "w")
file.write(note_value)
file.close()
When I try this I get the following error :
file = open("resources/user_notes/" + note_title + ".txt", "w")
FileNotFoundError: [Errno 2] No such file or directory: 'resources/user_notes/the.txt'
The directory I am using does exist, I have even copied the directory path from my file explorer to python, and it still doesn't work. If you know the solution to this please let me know.
Have you tried with joining?
import os
fn = os.path.join(os.path.dirname(__file__), '/resources/user_notes/the.txt')
with open(fn, 'r') as readfile:
for line in readfile:
print(line)
I encountered a similar problem while writing to multiple text files from Python. Most of the files had no issue, but a few resulted in
FileNotFoundError: [Errno 2] No such file or directory: 'IO/INDUSTRIES.txt'
Turns out the "/" in filename was causing the issue. This means that due to "/" my filename is "INDUSTRIES.txt" which resides in the "IO" folder, which is not true. So removing the "/" resolves this issue.
1.please check the working directory or change the relative path to absolute path.
2.make sure the variable note_title does not contains "/" or some other special character.
I created a project where my main.py script is in root folder Project. I have a utils directory inside and I want to get the path to this directory. I made a function which saves a .pdf file in my utils directory:
with open(os.path.abspath('utils/' + self.object.object_name+ '.pdf'), 'wb') as f:
f.write(pdf)
but I get an error:
IOError: [Errno 2] No such file or directory: '/home/documents/office/projects/me/utils/d.pdf'
How can I change os.path.abspath to do it the right way?
I want to get into utils directory always.
What you need is defining the path. And you can keep it relative.
yourPath = './utils/'
yourFileName = self.object.object_name+ '.pdf'
yourFullFileName = yourPath+yourFileName
and finally
with open(yourFullFileName, 'wb') as f:
f.write(pdf)
UPDATE
Following the small course Scott Hunter gave me, (cf his comment) I make amends. It follows that the correct way to build your path is :
working_dir = os.path.dirname(__file__)# __file__ is the full name of your working script
yourFullFileName = os.path.join(working_dir, 'util', self.object.object_name + "." + 'pdf')
By doing so, there is no assumption about the (operating-system dependent) separator.
I have a problem with my code. Basically what I want to do is naming the .txt file after a string associated with a variable.
If I use a "static" name it works:
output_txt = open("filename.txt", "w")
output_txt.close()
If I instead get the text from the content of a variable, it doesn't work:
output_txt = open("%s.txt" % var.my_variable, "w")
output_txt.close()
IOError: [Errno 2] No such file or directory: "content of my_variable"
my_variable is imported from a separate module and it's the result of a raw_input
Thanks.
I'll bet you have some directory structure in your variable. If there are forward slashes in the path to the filename and the directory doesn't exist, you will get the error you referenced. You can parse the input and check for the existence of the directory and possibly create it if it doesn't exist.