Reading text file read line by line not working
<p>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.</p>

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

<pre><code>with open('D:\filename.txt') as fp:
    for line in fp:
        print (line)
</code></pre>

<p>I copy pasted the above lines in command prompt but nothing is printing.</p>

<p>I have file with Sathiya as text.</p>

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

<p><a href="http://i.stack.imgur.com/gJ0yO.png" rel="nofollow"><img src="http://i.stack.imgur.com/gJ0yO.png" alt="enter image description here"></a></p>

<p><a href="http://i.stack.imgur.com/INaXz.png" rel="nofollow"><img src="http://i.stack.imgur.com/INaXz.png" alt="enter image description here"></a></p>

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

<p>You need to escape <code>\</code> char in the path:</p>

<pre><code>with open('D:\\filename.txt') as fp:
    for line in fp:
        print (line)
</code></pre>

<p>There some other ways for example you could use forward slashes:</p>

<pre><code>with open('D:/filename.txt') as fp:
    ...
</code></pre>

<p>Or you could use some helper methods:</p>

<pre><code>import os

file_path = os.path.join('d:', 'filename.txt')
with open(filename) as fp:
    ...
</code></pre>

<p>You can also use raw string.</p>

<pre><code>with open(r'D:\filename.txt') as fp:
    ...
</code></pre>

python python-3.x