Sathiya Kumar V M
Sathiya Kumar V M

Reputation: 517

Reading text file read line by line not working

I know there are too many questions were asked in this topic but still I'm not able to find the reason for my failure to read a text file line by line in Python.

I'm using Python 3.4.3 and I want to read a text file line by line.

with open('D:\filename.txt') as fp:
    for line in fp:
        print (line)

I copy pasted the above lines in command prompt but nothing is printing.

I have file with Sathiya as text.

I just want to print this text in my command prompt. What I'm doing wrong here?

enter image description here

enter image description here

Upvotes: 0

Views: 3019

Answers (1)

scriptmonster
scriptmonster

Reputation: 2771

The back slash (D:\filename.txt) in the filename escapes f char. That's why open could not find the file. To handle situation you can do the followings:

You need to escape \ char in the path:

with open('D:\\filename.txt') as fp:
    for line in fp:
        print (line)

There some other ways for example you could use forward slashes:

with open('D:/filename.txt') as fp:
    ...

Or you could use some helper methods:

import os

file_path = os.path.join('d:', 'filename.txt')
with open(filename) as fp:
    ...

You can also use raw string.

with open(r'D:\filename.txt') as fp:
    ...

Upvotes: 1

Related Questions