subrata paul
subrata paul

Reputation: 1

Python: Unable to open and read a file

I am totally new to python. I was trying to read a file which I already created but getting the below error

File "C:/Python25/Test scripts/Readfile.py", line 1, in <module>
    filename = open('C:\Python25\Test scripts\newfile','r')
IOError: [Errno 2] No such file or directory: 'C:\\Python25\\Test scripts\newfile

My code:

filename = open('C:\Python25\Test scripts\newfile','r')
print filename.read()

Also I tried

filename = open('C:\\Python25\\Test scripts\\newfile','r')
print filename.read()

But same errors I am getting.

Upvotes: 0

Views: 16553

Answers (5)

Ali
Ali

Reputation: 1

try to use slash ( / ) instead of backslash ( \ )

and also you should insert the full name of file, so instead of newfile insert newfile.txt

filename = open('C:/Python25/Test scripts/newfile.txt','r')
print filename.read()

Upvotes: 0

Sally Duan
Sally Duan

Reputation: 21

I am using VS code. If I am not using dent it would not work for the print line. So try to have the format right then you will see the magic.

with open("mytest.txt") as myfile:
    print(myfile.read())

or without format like this:

hellofile=open('mytest.txt', 'r')
print(hellofile.read())

Upvotes: 0

Harsha_Utd
Harsha_Utd

Reputation: 1

I had the same problem. Here's how I got it right.

your code:

filename = open('C:\\Python25\\Test scripts\\newfile','r')
print filename.read()

Try this:

with open('C:\\Python25\\Test scripts\\newfile') as myfile:
print(myfile.read())

Hope it helps.

Upvotes: 0

chrisdemeke
chrisdemeke

Reputation: 353

I think you're probably having this issue because you didn't include the full filename.

You should try:

filename = open('C:\Python25\Test scripts\newfile.txt','r')
print filename.read()

*Also if you're running this python file in the same location as the target file your are opening, you don't need to give the full directory, you can just call:

filename = open(newfile.txt

Upvotes: 0

Beri
Beri

Reputation: 11620

Try:

fpath = r'C:\Python25\Test scripts\newfile'
if not os.path.exists(fpath):
  print 'File does not exist'
  return

with open(fpath, 'r') as src:
  src.read()

First you validate that file, that it exists. Then you open it. With wrapper is more usefull, it closes your file, after you finish reading. So you will not stuck with many open descriptors.

Upvotes: 1

Related Questions