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 :>
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.