34

What is wrong with the following:

test_file=open('c:\\Python27\test.txt','r')
tshepang
  • 12,111
  • 21
  • 91
  • 136
Brian Teece
  • 343
  • 1
  • 3
  • 4
  • 1
    Your question doubles the backslash in one place but not the second. Your code uses single backslashes. Can you make the filename a raw string? – Eric Jablow Mar 24 '13 at 12:00

4 Answers4

83

\t is a tab character. Use a raw string instead:

test_file=open(r'c:\Python27\test.txt','r')

or double the slashes:

test_file=open('c:\\Python27\\test.txt','r')

or use forward slashes instead:

test_file=open('c:/Python27/test.txt','r')
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • What If I want to access an external file? Like below? This too gives the same error message. fileResp = open('https://www.google.co.in/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png', 'rb') – Krishna Gupta Apr 14 '20 at 09:27
  • 1
    @KrishnaGupta: `open()` can only access files, not URLs. – Martijn Pieters Apr 14 '20 at 14:00
3

\ is an escape character in Python. \t gets interpreted as a tab. If you need \ character in a string, you have to use \\.

Your code should be:
test_file=open('c:\\Python27\\test.txt','r')

twlkyao
  • 14,302
  • 7
  • 27
  • 44
Scintillo
  • 1,634
  • 1
  • 15
  • 29
2

always use 'r' to get a raw string when you want to avoid escape.

test_file=open(r'c:\Python27\test.txt','r')
Yarkee
  • 9,086
  • 5
  • 28
  • 29
1

\t in a string marks an escape sequence for a tab character. For a literal \, use \\.

twlkyao
  • 14,302
  • 7
  • 27
  • 44
svk
  • 5,854
  • 17
  • 22