Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read a file in other directory in python

Tags:

python

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 :

import os os.getcwd() os.path.exists(direct) 

the result was
True

x_file=open(direct,'r')   

and I got this error :

Traceback (most recent call last): File "<pyshell#17>", line 1, in <module> x_file=open(direct,'r') IOError: [Errno 13] Permission denied 

I don't know why I can't read the file ? Any suggestions?

thanks .

like image 277
mzn.rft Avatar asked Nov 04 '12 22:11

mzn.rft


People also ask

How do I see files in a directory in Python?

To get a list of all the files and folders in a particular directory in the filesystem, use os. listdir() in legacy versions of Python or os. scandir() in Python 3. x.


2 Answers

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") 
like image 161
alexis Avatar answered Oct 14 '22 06:10

alexis


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.

like image 23
braunmagrin Avatar answered Oct 14 '22 05:10

braunmagrin