How to read a file in other directory in python

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

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

    x_file = open(os.path.join(direct, '5_1.txt'), 'r')

    0 讨论(0)
  • 2020-12-13 14:05

    As error message said your application has no permissions to read from the directory. It can be the case when you created the directory as one user and run script as another user.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-13 14:07

    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
    
    0 讨论(0)
提交回复
热议问题