How to read a file in other directory in python

前端 未结 8 1244
暖寄归人
暖寄归人 2020-12-13 13:46

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 :

8条回答
  •  [愿得一人]
    2020-12-13 14:07

    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.

提交回复
热议问题