Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem opening a text file in Python

Tags:

python

This seems like 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?

like image 393
startuprob Avatar asked Apr 25 '11 19:04

startuprob


2 Answers

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.

like image 77
nmichaels Avatar answered Sep 30 '22 15:09

nmichaels


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'

like image 23
eyquem Avatar answered Sep 30 '22 16:09

eyquem