Python reads \\ when \ is the input - python

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.

Related

Directory parameter on Windows has trailing backslash replaced with double quote when passed to Python

I am seeing an annoying trailing double quote when passing in a quoted directory in Windows to Python.
This is my Python test program, print_args.py:
import sys
print(sys.argv)
This is what I get when I run it from the command line. Note that the quoted directory is the standard format generated by tab completion in the Windows shell. The double quotes are needed because of the spaces in the path.
>py print_args.py -test "C:\Documents and Settings\"
['print_args.py', '-test', 'C:\\Documents and Settings"']
The trailing backslash has been replaced with a double quote, presumably because Python is reading it as a quoted double quote, rather than matching it to the leading quote.
If instead of passing the parameter to Python, I pass it to a batch script which just echoes it, then I get the trailing backslash as expected.
So somewhere between the CMD shell and Python seeing sys.argv there has been some parsing which has affected backslashes and double quotes.
Can anyone illuminate?
Edited to add:
Further reading suggests to me that Python is doing some parsing of the windows command line arguments to construct sys.argv. I think Windows passes the entire command line string, in this case mostly unchanged, to Python and Python uses its own internal logic to break it into the strings in the sys.argv list. This processing must allow escaped double quotes as a special case. I would be pleased to see some documentation or the code...
Command line processing on Windows is not completely standardised but in the case of Python and many other programs it uses the Microsoft C runtime behaviour. This is specified, for example, here. It says
A string surrounded by double quote marks is interpreted as a single argument, which may contain white-space characters. [...] If the command line ends before a closing double quote mark is found, then all the characters read so far are output as the last argument.
A double quote mark preceded by a backslash (") is interpreted as a literal double quote mark (").
The second of these two rules prevents the second double quote being read as terminating the argument - instead a double quote is appended. Then the first rule allows the argument to end without a terminating double quote.
Note that this section also says
The command line parsing rules used by Microsoft C/C++ code are Microsoft-specific.
This is even more confusing when using PowerShell.
PS> py print_args.py -test 'C:\Documents and Settings\'
['print_args.py', '-test', 'C:\\Documents and Settings"']
Here PowerShell parsing preserves the final backslash and drops the single quotes. Then it adds double quotes (because of the spaces in the path) before passing the command line to the C runtime which parses it according to the rules, escaping the double quote added by PowerShell.
However, this all does conform to the documented behaviour and is not a bug.
You need to escape the backslash, since a backslash itself is the escape character for both Python and PowerShell. Otherwise, \" means passing in a " literal instead of using it to enclose the string. The following works fine for me:
PS> py print_args.py -test "C:\\Documents and Settings\\"
Output:
['rando.py', '-test', 'C:\\Documents and Settings\\']

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 "\"

Understanding Backslash Behaviour (Windows)

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'

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 "\"

Categories

Resources