How to read a file in other directory in python

前端 未结 8 1232
暖寄归人
暖寄归人 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:13

    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")   
    
    0 讨论(0)
  • 2020-12-13 14:15

    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.

    0 讨论(0)
提交回复
热议问题