Problem opening a text file in Python

后端 未结 2 1810
孤独总比滥情好
孤独总比滥情好 2021-02-10 01:49

This seems like it should be very easy:

f = open(\'C:\\Users\\john\\Desktop\\text.txt\', \'r\')

But I am getting this error:

           


        
2条回答
  •  情书的邮戳
    2021-02-10 02:18

    In Windows, paths use backslash. But if a string that must represent a path contains characters such as '\r' , '\t' , '\n' .... etc there will be this kind of problem. This is the precise reason why your string fails to represent a path.

    In the absence of these problematic characters, there will be no problem. If they are present, you must escape the backslashes or use a raw string r'C:\Users\john\Desktop\text.txt'

提交回复
热议问题