Getting a FileNotFoundError for writing a text file - python

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.

Related

Python error: FileNotFoundError: [Errno 2] No such file or directory

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.

Python - set path to the directory in project

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.

Python - filename named after the content of a variable: IOError: [Errno 2] No such file or directory:

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.

Cannot open file in Python "No such file or directory" error

I've been trying to download files from an FTP server. For this I've found this Python-FTP download all files in directory and examined it. Anyways, I extracted the code I needed and it shows as follows:
import os
from ftplib import FTP
ftp = FTP("ftp.example.com", "exampleUsername", "examplePWD")
file_names = ftp.nlst("\public_html")
print file_names
for filename in file_names:
if os.path.splitext(filename)[1] != "":
local_filename = os.path.join(os.getcwd(), "Download", filename)
local_file = open(filename, 'wb')
ftp.retrbinary('RETR ' + filename, local_file.write)
local_file.close()
ftp.close()
But when it tries to open the file, it keeps saying:
ftplib.error_perm: 550 Can't open CHANGELOG.php: No such file or directory
I've tried w+, a+, rw, etc. and I keep getting the same error all the time. Any ideas?
Note: I am using OSX Mavericks and Python 2.7.5.
This question may have been asked several times and believe me I researched and found some of them and none of them worked for me.
open() in Python does not create a file if it doesn't exist
ftplib file select
It looks like you are listing files in a directory and then getting files based on the returned strings. Does nlst() return full paths or just filenames? If its just filenames than retrbinary might be expecting "/Foo/file" but getting "file", and there might not be anything named file in the root dir of the server.

Unable to write file in python

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.

Categories