Reading from file in Python, weird error

前端 未结 1 1307
悲哀的现实
悲哀的现实 2021-01-25 05:36
 f = open(\"‪C:\\Users\\aleed_000\\Desktop\\dis.txt\",\"r\")
 print (f.read())
 f.close()

Can anyone explain why this doesn\'t read from my file named

相关标签:
1条回答
  • 2021-01-25 05:48

    Use a raw string or escape each '\' by prefixing another '\' to it:

    because C:\Users\aleed_000\Desktop\dis.txt is actually interpreted like this:

    >>> print ("‪C:\Users\aleed_000\Desktop\dis.txt") # '\a' gets escaped
    C:\Usersleed_000\Desktop\dis.txt
    

    Raw string:

    >>> print (r"‪C:\Users\aleed_000\Desktop\dis.txt")  #notice the r at the start
    C:\Users\aleed_000\Desktop\dis.txt
    

    Escape each '\':

    >>> print ("‪C:\\Users\\aleed_000\\Desktop\\dis.txt")
    C:\Users\aleed_000\Desktop\dis.txt
    
    0 讨论(0)
提交回复
热议问题