This question already has answers here:
How should I write a Windows path in a Python string literal?
(5 answers)
Closed 2 years ago.
When setting a string to a filepath in Python for WIndows, does it need to be formatted as:
C:\\Users\\
Or do escapes not apply on Windows? My script is currently giving me something like "Non-ASCII character" at the line import os, so I can't really test this.
Try adding an "r", do as below:
path = r"C:\mypaht\morepaht\myfie.file"
Short answer: Use forward slash instead as suggested by gnibbler.
On using raw strings:
Using a raw string usually works fine, still you have to note that r"\"" escapes the quoute char. That is, raw string is not absolutely raw and thats the reason why you cant use backslash (or any odd number of backslashes) in the end of a string like '\' (the backslash would escape the following quote character).
In [9]: a=r'\\'
In [10]: b=r'\\\'
File "<ipython-input-10-9f86439e68a3>", line 1
b=r'\\\'
^
SyntaxError: EOL while scanning string literal
In [11]: a
Out[11]: '\\\\'
You should not construct file paths that way. Its not portable and error prone.
Use the join() function from os.path
import os.path
path = os.path.join('C:', 'Users', 'name')
Related
Is there a way to declare a string variable in Python such that everything inside of it is automatically escaped, or has its literal character value?
I'm not asking how to escape the quotes with slashes, that's obvious. What I'm asking for is a general purpose way for making everything in a string literal so that I don't have to manually go through and escape everything for very large strings.
Raw string literals:
>>> r'abc\dev\t'
'abc\\dev\\t'
If you're dealing with very large strings, specifically multiline strings, be aware of the triple-quote syntax:
a = r"""This is a multiline string
with more than one line
in the source code."""
There is no such thing. It looks like you want something like "here documents" in Perl and the shells, but Python doesn't have that.
Using raw strings or multiline strings only means that there are fewer things to worry about. If you use a raw string then you still have to work around a terminal "\" and with any string solution you'll have to worry about the closing ", ', ''' or """ if it is included in your data.
That is, there's no way to have the string
' ''' """ " \
properly stored in any Python string literal without internal escaping of some sort.
You will find Python's string literal documentation here:
http://docs.python.org/tutorial/introduction.html#strings
and here:
http://docs.python.org/reference/lexical_analysis.html#literals
The simplest example would be using the 'r' prefix:
ss = r'Hello\nWorld'
print(ss)
Hello\nWorld
(Assuming you are not required to input the string from directly within Python code)
to get around the Issue Andrew Dalke pointed out, simply type the literal string into a text file and then use this;
input_ = '/directory_of_text_file/your_text_file.txt'
input_open = open(input_,'r+')
input_string = input_open.read()
print input_string
This will print the literal text of whatever is in the text file, even if it is;
' ''' """ “ \
Not fun or optimal, but can be useful, especially if you have 3 pages of code that would’ve needed character escaping.
Use print and repr:
>>> s = '\tgherkin\n'
>>> s
'\tgherkin\n'
>>> print(s)
gherkin
>>> repr(s)
"'\\tgherkin\\n'"
# print(repr(..)) gets literal
>>> print(repr(s))
'\tgherkin\n'
>>> repr('\tgherkin\n')
"'\\tgherkin\\n'"
>>> print('\tgherkin\n')
gherkin
>>> print(repr('\tgherkin\n'))
'\tgherkin\n'
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 "\"
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.
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 "\"
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Process escape sequences in a string in Python
If I get this string, for example from a web form:
'\n test'
The '\n' notation won't be interpreted as a line break. How an I parse this string so it becomes a line break?
Of course I can use replace, split, re, etc, to do it manually.
But maybe there is a module for that, since I don't want to be forced to deal with all the \something notations manually.
I tried to turn it into bytes then use str as a construtor but that doesn't work:
>>> str(io.BytesIO(ur'\n'.encode('utf-8')).read())
'\\n'
Use .decode('string_escape')
>>> print "foo\\nbar\\n\\tbaz"
foo\nbar\n\tbaz
>>> print "foo\\nbar\\n\\tbaz".decode('string_escape')
foo
bar
baz
As I'm typing in code, the above have to escape the \ to make the string contain the 2 characters \n
Edit: actually this is a duplicate of Process escape sequences in a string in Python