How to read a file in other directory in python
How to read a file in other directory in python
--
Become part of the top 3% of the developers by applying to Toptal
https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Romantic Lands Beckon
--
Chapters
00:00 Question
00:47 Accepted answer (Score 30)
01:15 Answer 2 (Score 11)
01:46 Answer 3 (Score 5)
02:42 Answer 4 (Score 2)
03:05 Thank you
--
Full question
https://stackoverflow.com/questions/1322...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python
#avk47
ACCEPTED ANSWER
Score 31
Looks like you are trying to open a directory for reading as if it's a regular file. Many OSs won't let you do that. You don't need to anyway, because what you want (judging from your description) is
x_file = open(os.path.join(direct, "5_1.txt"), "r")
or simply
x_file = open(direct+"/5_1.txt", "r")
ANSWER 2
Score 11
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.
ANSWER 3
Score 5
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.
ANSWER 4
Score 2
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