I am trying to create a directory in my Python code but I can't use backslash \ in a string. Every time I do it gives me an unexpected token error.
I would like my code to look something like this:
dir = os.getcwd() + "\FolderIWantToCreate"
If I use / (forward slash), it gives me an error because my directory paths use backslash. However if I type \ (backslash) anywhere in my code, even inside "", it doesn't register the backslash as a string, it says unexpected token.
How can I overcome this?
\ is the escape character in python. If you want to use \ in a string you have to escape it, i.e.:
"\\"
For more, see: https://docs.python.org/2.0/ref/strings.html
You have two options:
You can either escape the escape character \ by adding an extra \ before it, like this: "\\FolderIWantToCreate",
You can use the r prefix before the string to tell python that the string that follows is a raw string, like this: r"\FolderIWantToCreate"
If you are dealing with paths and look e.g. for OS intercompatibility, consider using the pathlib package. More info on how to use it when e.g. creating new folders, see here.
If you really have to use that notation anyways, then an option would be to make it a "raw" string:
s = r'\FolderIWantToCreate'
more on that e.g. here.
Please use the Escape sequence when ever you are using special characters
dir = os.getcwd() + "\\FolderIWantToCreate"
Reference : 2.4.1 String literals
dir = os.getcwd() + "\\FolderIWantToCreate"
Just adding another answer which I think you should know;
Assuming you are on Windows
You can use os.path.join() with os.sep to overcome the issue you are facing.
I do not have a Windows VM with me to give you a concrete example.
Related
I would like to replace the backslash \ in a windows path with forward slash / using python.
Unfortunately I'm trying from hours but I cannot solve this issue.. I saw other questions here but still I cannot find a solution
Can someone help me?
This is what I'm trying:
path = "\\ftac\admin\rec\pir"
path = path.replace("\", "/")
But I got an error (SyntaxError: EOL while scanning string literal) and is not return the path as I want:
//ftac/admin/rec/pir, how can I solve it?
I also tried path = path.replace(os.sep, "/") or path = path.replace("\\", "/") but with both methods the first double backslash becomes single and the \a was deleted..
Oh boy, this is a bit more complicated than first appears.
Your problem is that you have stored your windows paths as normal strings, instead of raw strings. The conversion from strings to their raw representation is lossy and ugly.
This is because when you make a string like "\a", the intperter sees a special character "\x07".
This means you have to manually know which of these special characters you expect, then [lossily] hack back if you see their representation (such as in this example):
def str_to_raw(s):
raw_map = {8:r'\b', 7:r'\a', 12:r'\f', 10:r'\n', 13:r'\r', 9:r'\t', 11:r'\v'}
return r''.join(i if ord(i) > 32 else raw_map.get(ord(i), i) for i in s)
>>> str_to_raw("\\ftac\admin\rec\pir")
'\\ftac\\admin\\rec\\pir'
Now you can use the pathlib module, this can handle paths in a system agnsotic way. In your case, you know you have Windows like paths as input, so you can use as follows:
import pathlib
def fix_path(path):
# get proper raw representaiton
path_fixed = str_to_raw(path)
# read in as windows path, convert to posix string
return pathlib.PureWindowsPath(path_fixed).as_posix()
>>> fix_path("\\ftac\admin\rec\pir")
'/ftac/admin/rec/pir'
I created about 200 csv files in Python and now need to download them all.
I created the files from a single file using:
g = df.groupby("col")
for n,g in df.groupby('col'):
g.to_csv(n+'stars'+'.csv')
When I try to use this same statement to export to my machine I get a syntax error and I'm not sure what I'm doing wrong:
g = df.groupby("col")
for n,g in df.groupby('col'):
g.to_csv('C:\Users\egagne\Downloads\'n+'stars'+'.csv'')
Error:
File "<ipython-input-27-43a5bfe55259>", line 3
g.to_csv('C:\Users\egagne\Downloads\'n+'stars'+'.csv'')
^
SyntaxError: invalid syntax
I'm in Jupyter lab, so I can download each file individually but I really don't want to have to do that.
You're possibly mixing up integers and strings, and the use of backslash in literals is dangerous anyway. Consider using the following
import os
inside the loop
f_name = os.path.join('C:', 'users', ' egagne', 'Downloads', str(n), 'stars.csv')
g.to_csv(f_name)
with os.path.join taking care of the backslashes for you.
g.to_csv('C:\Users\egagne\Downloads\'n+'stars'+'.csv'')
needs to be
g.to_csv('C:\\Users\\egagne\\Downloads\\'+n+'stars.csv').
There were two things wrong -- the backslash is an escape character so if you put a ' after it, it will be treated as part of your string instead of a closing quote as you intended it. Using \\ instead of a single \ escapes the escape character so that you can include a backslash in your string.
Also, you did not pair your quotes correctly. n is a variable name but from the syntax highlighting in your question it is clear that it is part of the string. Similarly you can see that stars and .csv are not highlighted as part of a string, and the closing '' should be a red flag that something has gone wrong.
Edit: I addressed what is causing the problem but Ami Tavory's answer is the right one -- though you know this is going to run on windows it is a better practice to use os.path.join() with directory names instead of writing out a path in a string. str(n) is also the right way to go if you are at all unsure about the type of n.
I have often seen syntax like this in python code.
import os
os.chdir(r'C:\Users\test\Desktop')
I was wondering why would I need to give r before the path, I believe it has something to do with '\' in the path , Is there any other way to give path instead of using r''
It makes sure that the backslash doesn't escape the characters. It's same as
os.chdir('C:\\Users\\test\\Desktop')
'r' before string literal make Python parse it as a "raw" string, without escaping.
If you want not to use 'r' before string literal, but specify path with single slashes, you can use this notation:
"C:/Users/test/Desktop"
As it would be in unix-pased systems. Windows understand both "\" and "/" in file paths, so, using "/" give you ability to avoid 'r' letter before the path string.
Also, as it was mentioned, you can specify path with double slashes, but, as I realized, this is not that you wanted:
"C:\\Users\\test\\Desktop"
You can use forward slashes in Windows as well, so you dont need raw string literals:
>>> import os
>>> os.stat(r'C:\Users\f3k\Desktop\excel.vbs')
nt.stat_result(st_mode=33206, st_ino=0L, st_dev=0, st_nlink=0, st_uid=0, st_gid=0, st_size=555L, st_atime=1367585162L, st_mtime=1367586148L, st_ctime=1367585162L)
Same using forward slashes:
>>> os.stat('C:/Users/f3k/Desktop/excel.vbs')
nt.stat_result(st_mode=33206, st_ino=0L, st_dev=0, st_nlink=0, st_uid=0, st_gid=0, st_size=555L, st_atime=1367585162L, st_mtime=1367586148L, st_ctime=1367585162L)
But take care using os.path.join():
>>> os.path.join('C:/Users/f3k/Desktop', 'excel.vbs')
'C:/Users/f3k/Desktop\\excel.vbs'
Only when it has escape sequences
print('C:\sys\cat\Desktop')
Better to give it as raw type to avoid the glitches or using forward slash.
As per knowledge, you can use forward slash instead of backward slash and put r on it. If you use a backslash then you have to put r in front of it or you can do a forward slash if you want to.
Example - > You can try this in Jupyter notebook:
f = open(r'F:\love.txt', 'r')
or
f = open('F:/love.txt', 'r')
Both will work fine.
I'm trying to escape the backslash, but trying to understand the right way of doing it
foo = r'C:\Users\test.doc'
The above works fine
However, when I want to escape the path stored in a variable
For example :
parser.add_argument('-s', '--source', type = str, help = 'Source file path')
Now, how do escape the value in - args.source
So there are a few escape sequences to be aware of in python and they are mainly these.
So when the string for that file location is parsed by the add_argument method it may not be interpreted as a raw string like you've declared and there will be no way to escape the backslashes outside of the declaration.
What you can do instead is to keep it as a regular string (removing the 'r' prefix from the string) and using the escape character for a backslash in any places there may be conflict with another escape character (in this case \t). This may work as the method may evaluate the string correctly.
Try declaring your string like this.
foo = "C:\Users\\test.doc"
Hopefully this helps fix your issue!
EDIT:
In response to handling the dynamic file location you could maybe do something like the following!
def clean(s):
s = s.replace("\t", "\\t")
s = s.replace("\n", "\\n")
return s
Until you've covered all of your bases with what locations you may need to work with! This solution might be more appropriate for your needs. It's kind of funny I didn't think of doing it this way before. Hopefully this helps!
I get an error on the [(] bracket opening the file. Please help :)
usedbeforefile = open&&(&&'c:\\Documents and Settings\Adam\Desktop\NewProgram\Resources\Alfred\ub4.txt')
EDIT: Thank you, Ashwini Chaudhary
(If you see the '&&' around the bracket that is just me showing where my error was :D)
Try this:
usedbeforefile = open(r'c:\Documents and Settings\Adam\Desktop\NewProgram\Resources\Alfred\ub4.txt')
Notice the r before the start of the string. That's the way to say: this is a raw string, there's no need to interpret \ as a special escape character. Another alternative would be to use normal strings and manually escape all \ characters:
usedbeforefile = open('c:\\Documents and Settings\\Adam\\Desktop\\NewProgram\\Resources\\Alfred\\ub4.txt')
You can also use forward slashes on Unix and Windows because Python tries to interpret path portably.
usedbeforefile = open('c:/Documents and Settings/Adam/Desktop/NewProgram/Resources/Alfred/ub4.txt')