Problem opening a text file in Python

后端 未结 2 1811
孤独总比滥情好
孤独总比滥情好 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'

    0 讨论(0)
  • 2021-02-10 02:43

    Your file name has backslash characters in it. Backslash is the escape character in Python strings. Either replace them with '/' characters or use r'C:\Users\john\Desktop\text.txt'.

    You might also find the functions in os.path useful.

    0 讨论(0)
提交回复
热议问题