Understanding Backslash Behaviour (Windows) - python

I declare variable 'path'
path = "C:\\dir\\file.zip"
Because the first slash escapes the second, and so
print path
>>>C:\dir\file.zip
However, when I try to unzip the file
inF = gzip.GzipFile(path, 'rb')
I get the error
IOError: [Errno 2] No such file or directory: 'C:\\dir\\file.gz'
How are these additional backslashes appearing, and how can I fix it?
TIA

Those additional backslashes are there to make the string unambiguous, as it might have contained quotes, newlines and such. IOError has printed the repr form of the string, such that the value can be recreated by copying it into Python code:
>>> path = "C:\\dir\\file.zip"
>>> print path
C:\dir\file.zip
>>> print repr(path)
'C:\\dir\\file.zip'
So the extra backslashes are simply the same escaping you did in the first place, and have no impact on the error itself.

'\' is used to vanish the special meaning of any character like '' or "" or '\' and manu other.
rawstring do the same for you check here
instead
path = "C:\\dir\\file.zip"
path = r'C:\dir\file.zip'
>>> print 'C:\\dir\\file.zip'
C:\dir\file.zip
>>> print (r'C:\Users\dir\file.zip')
C:\dir\file.zip
>>> print (ur'C:\\Users\dir\file.zip') #ur'' as unicode string literals with \u or \U sequences are broken in python2 and several backslashes are treated as one on windows
Use forward slashes rahter than backward slashes
>>> a = 'C:/User/dir/file.zip'
>>> a
'C:/User/dir/file.zip'

Related

basic .json storage and retrieval [duplicate]

I need to put a lot of filepaths in the form of strings in Python as part of my program. For example one of my directories is D:\ful_automate\dl. But Python recognizes some of the characters together as other characters and throws an error. In the example the error is IOError: [Errno 22] invalid mode ('wb') or filename: 'D:\x0cul_automate\\dl. It happens a lot for me and every time I need to change the directory name to one that may not be problematic.
The \ character is used to form character escapes; \f has special meaning.
Use / or use raw string r'' instead. Alternatively, you could ensure that Python reads the backslash as a backslash by escaping it with an additional \.
r'D:\ful_automate\dl'
'D:\\ful_automate\\dl'
'D:/ful_automate/dl'
Demo to show the difference:
>>> 'D:\ful_automate\dl'
'D:\x0cul_automate\\dl'
>>> r'D:\ful_automate\dl'
'D:\\ful_automate\\dl'
Use raw string instead of string ie
use r'filepath'
It fixes the problem off blacklash "\"

Python reads \\ when \ is the input

I am trying to create a new text file in an empty folder. The path to the folder is:
C:\Users\Tor\Desktop\Python files\retning
When I type this in the command line in windows explorer, I get straight to the empty folder.
When I type my code in Python I get an errormessage and it looks like Python has replaced a couple of the '\' with '\\'
This is my code
sector='A5'
g=open('C:\Users\Tor\Desktop\Python files\retning\retning'+sector+'.txt', 'a')
and this is the errormessage
Traceback (most recent call last):
File "C:\Users\Tor\Desktop\Python files\filer som behandler output\Vindretning.py", line 2, in <module>
g=open('C:\Users\Tor\Desktop\Python files\retning\retning'+sector+'.txt', 'a')
IOError: [Errno 22] invalid mode ('a') or filename: 'C:\\Users\\Tor\\Desktop\\Python files\retning\retningA5.txt'
Can anyone please tell me what I am doing wrong, or what is happening here?
\ needs to be escaped in the strings. That is why \\ or raw strings are used (r'test String')
Using raw strings solves the problem here. Something like,
open(r'C:\Programming Test Folder\test_file.py')
So, your code gets changed to
g=open(r'C:\Users\Tor\Desktop\Python files\retning\retning{}.txt'.format(sector), 'a')
Or use / in Windows, like follows
g=open('C:/Users/Tor/Desktop/Python files/retning/retning'+sector+'.txt', 'a')
This is normal behaviour; Python is giving you a string representation that can be pasted right back into a Python script or interpreter prompt. Since \ is a character used in Python string literals to start an escape sequence (such as \n or \xa0) the backslashes are doubled.
In fact, it is the characters without escaped backslashes that are the key here; \r is the escape code for a carriage return. You need to use one of the following options to specify Windows paths instead:
Escape all backslashes by doubling them in your string literals:
g = open('C:\\Users\\Tor\\Desktop\\Python files\\retning\\retning'+sector+'.txt', 'a')
Now the \r won't be interpreted as an escape code.
Use a raw string literal:
g = open(r'C:\Users\Tor\Desktop\Python files\retning\retning'+sector+'.txt', 'a')
In raw string literals most escape codes are ignored.
Use forward slashes:
g = open('C:/Users/Tor/Desktop/Python files/retning/retning'+sector+'.txt', 'a')
Forward slashes work fine as path separators on Windows, and there's no chance of them being interpreted as escape characters.
In a normal python string, a backslash can have a special meaning (for instance, \n indicates a new line). In the path you've provided in your code, you either need to use \\ for each directory separator (\\ means include a ), or mark the string as a raw string, meaning the special treatment for backslashes doesn't apply. You do that with an r before the quote mark, like r'Folder\Sub-Folder\Another'
The error message is basically python giving you the python code you can use to get your original string.

error "invalid filename" if i use letters a to f in file name

i'm using pyton 2.7. I have written a script , when it is executed, it will call and run some other file with the name abc.py. but i'm getting error
IOError: [Errno 22] invalid mode ('r') or filename: 'F:\x07bc.c'
it is working fine if i change the file name.
it shows error only if i use letters from a to f as the first letter of file name
Please help.
Thank you
Consider the Python string '\a'. As described in the documentation, the back slash character is interpreted as an escape character. So '\a' is in fact the ASCII Bell character, character number 7.
Your filename is 'F:\abc.c' and the \a in there is interpreted as ASCII Bell. You can see this clearly in the interpretor:
>>> 'F:\abc.c'
'F:\x07bc.c'
>>> print 'F:\abc.c'
F:bc.c
When you print that string note that the \a does not appear. That's because it has been turned into a Bell control character which is invisible.
To include a backslash you can use the correct escape sequence \\. Put it all together and your filename should be: 'F:\\abc.c'. As an alternative, you can prefix the string with r to make it a raw string. This is also detailed in the documentation.
>>> 'F:\\abc.c'
'F:\\abc.c'
>>> print 'F:\\abc.c'
F:\abc.c
>>> r'F:\abc.c'
'F:\\abc.c'
>>> print r'F:\abc.c'
F:\abc.c
Try this:
open(r'F:\abc.c')
i.e. add r before quotes.
UPDATE Sorry, I misinterpreted the code (although my solution is correct). #DavidHeffernan is right, the \a is read as the ASCII bell.
Escape the \ with another backslash, like this:
print 'F:\\x07bc.c'

File paths in Python in the form of string throw errors

I need to put a lot of filepaths in the form of strings in Python as part of my program. For example one of my directories is D:\ful_automate\dl. But Python recognizes some of the characters together as other characters and throws an error. In the example the error is IOError: [Errno 22] invalid mode ('wb') or filename: 'D:\x0cul_automate\\dl. It happens a lot for me and every time I need to change the directory name to one that may not be problematic.
The \ character is used to form character escapes; \f has special meaning.
Use / or use raw string r'' instead. Alternatively, you could ensure that Python reads the backslash as a backslash by escaping it with an additional \.
r'D:\ful_automate\dl'
'D:\\ful_automate\\dl'
'D:/ful_automate/dl'
Demo to show the difference:
>>> 'D:\ful_automate\dl'
'D:\x0cul_automate\\dl'
>>> r'D:\ful_automate\dl'
'D:\\ful_automate\\dl'
Use raw string instead of string ie
use r'filepath'
It fixes the problem off blacklash "\"

Python: Writing raw strings to a file

I want to generate C code with a Python script, and not have to escape things. For example, I have tried:
myFile.write(someString + r'\r\n\')
hoping that a r prefix would make things work. However, I'm still getting the error:
myFile.write(someString + ur'\r\n\')
^
SyntaxError: EOL while scanning string literal
How can I write raw strings to a file in Python?
Python raw stings can't end with a backslash.
However, there are workarounds.
You can just add a whitespace at the end of the string:
>>> with open("c:\\tmp\\test.txt", "w") as myFile:
... myFile.write(someString + r'\r\n\ ')
You propably don't bother with that, so that may be a solution.
Assume someString is Hallo.
This will write Hallo\r\n\_ to the file, where _ is a space.
If you don't like the extra space, you can remove it like this:
>>> with open("c:\\tmp\\test.txt", "w") as myFile:
... myFile.write(someString + r'\r\n\ '[:-1])
This will write Hallo\r\n\ to the file, without the extra whitespace, and without escaping the backslash.
You need to escape the last \ so it doesn't escape the end of string, but if you put it as part of a raw string, it won't get you exactly what you want:
>>> r'\r\n\\'
'\\r\\n\\\\'
Python's string literal concatenation, however, lets you mix raw and normal strings:
>>> r'\r\n' '\\'
'\\r\\n\\'
You could insert the raw string into the string via the format method. This ensures
that the raw string will be inserted with the proper escaping.
Example:
mystring = "some string content {0}"
# insert raw string
mystring = mystring.format(r"\r\n\\")
myfile = open("test.txt", "w")
myfile.write(mystring)
myfile.close()
myFile.write(someString + r'\r\n\\')
Just escape your strings ^^
There is no way to have a string literal of arbitrary contents without escaping. You will always run into problems, since there is no way of for example having the "end-of-literal character", in this case ' there without escaping, as Python would be unable to tell if it is the end of the string literal or part of it.
And that's the entire reason why we have escaping in the first place. So the answer to your question is: You can't. Not in Python nor any other language.

Categories

Resources