Problem opening a text file in Python
This seems like 开发者_StackOverflow中文版it should be very easy:
f = open('C:\Users\john\Desktop\text.txt', 'r')
But I am getting this error:
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
f = open('C:\Users\john\Desktop\text.txt', 'r')
IOError: [Errno 22] invalid mode ('r') or filename: 'C:\\Users\robejohn\\Desktop\text.txt'
Any thoughts?
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.
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'
精彩评论