How to read a file in other directory in python

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

    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.

提交回复
热议问题