Reputation: 873
In my python script I declare a path to a file like so:
input_file = "C:\Path\To\My\File One.csv"
And I use this block of code to open the file:
with open(input_file, 'rb') as csvinput:
print csvinput
When I open this file, it opens successfully returning:
<open file 'C:\\Path\\To\My\\Folder\\File One.csv', mode 'rb' at 0x02CD37B0>`
However when I try and use the same block of code to open:
input_file = "C:\Path\To\My\Folder\File Two.csv"
I get the following error:
IOError: [Errno 22] invalid mode ('rb') or filename: 'C:\\Path\\To\\My\\Folder\File Two.csv'
Why do all the backslashes get escaped from the first file path but not in the second file path? If I use r'input_file = "C:\Path\To\My\Folder\File Two.csv'
the file opens as expected. Why don't I have to do the same for File One.csv
? I've looked at both files but can't seem to see any differences that would cause this.
Upvotes: 1
Views: 80
Reputation: 1626
Your problem is likely the use of single backslashes, though I cannot be sure without the actual filenames. My guess is the first letter of your second filename is a valid escape sequence when combined with a backslash (i.e. something like \n
for newline), while the first letter of the first filename is not.
If python does not recognize the escape sequence, it puts it in verbatim, which is why the other backslashes are fine. The rules for string escape sequences are here. I recommend always using raw strings (i.e. string literals like r"C:\My Path\My File.txt"
), or using double backslashes.
Upvotes: 2