I have a file named 5_1.txt
in a directory named direct
, how can I read that file using read
?
I verified the path using :
import os
os.getcwd()
os.path.exists(direct)
the result was
True
x_file=open(direct,'r')
and I got this error :
Traceback (most recent call last):
File "<pyshell#17>", line 1, in <module>
x_file=open(direct,'r')
IOError: [Errno 13] Permission denied
I don't know why I can't read the file ? Any suggestions?
thanks .
This question is related to
python
You can't "open" a directory using the open
function. This function is meant to be used to open files.
Here, what you want to do is open the file that's in the directory. The first thing you must do is compute this file's path. The os.path.join
function will let you do that by joining parts of the path (the directory and the file name):
fpath = os.path.join(direct, "5_1.txt")
You can then open the file:
f = open(fpath)
And read its content:
content = f.read()
Additionally, I believe that on Windows, using open
on a directory does return a PermissionDenied
exception, although that's not really the case.
In case you're not in the specified directory (i.e. direct), you should use (in linux):
x_file = open('path/to/direct/filename.txt')
Note the quotes and the relative path to the directory.
This may be your problem, but you also don't have permission to access that file. Maybe you're trying to open it as another user.
As error message said your application has no permissions to read from the directory. It can be the case when you created the directory as one user and run script as another user.
For windows you can either use the full path with '\\' ('/' for Linux and Mac) as separator of you can use os.getcwd to get the current working directory and give path in reference to the current working directory
data_dir = os.getcwd()+'\\child_directory'
file = open(data_dir+'\\filename.txt', 'r')
When I tried to give the path of child_diectory entirely it resulted in error. For e.g. in this case:
file = open('child_directory\\filename.txt', 'r')
Resulted in error. But I think it must work or I am doing it somewhat wrong way but it doesn't work for me. The about way always works.
i found this way useful also.
import tkinter.filedialog
from_filename = tkinter.filedialog.askopenfilename()
here a window will appear so you can browse till you find the file , you click on it then you can continue using open , and read .
from_file = open(from_filename, 'r')
contents = from_file.read()
contents
x_file = open(os.path.join(direct, '5_1.txt'), 'r')
For folks like me looking at the accepted answer, and not understanding why it's not working, you need to add quotes around your sub directory, in the green checked example,
x_file = open(os.path.join(direct, "5_1.txt"), "r")
should actually be
x_file = open(os.path.join('direct', "5_1.txt"), "r")
Source: Stackoverflow.com