I get error in bracket opening a file in Python - python

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')

Related

How do I use \ in a string?

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.

Exporting multiple csv files with dynamic naming

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.

Python escaping backslash

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!

Print raw string from variable? (not getting the answers)

I'm trying to find a way to print a string in raw form from a variable. For instance, if I add an environment variable to Windows for a path, which might look like 'C:\\Windows\Users\alexb\', I know I can do:
print(r'C:\\Windows\Users\alexb\')
But I cant put an r in front of a variable.... for instance:
test = 'C:\\Windows\Users\alexb\'
print(rtest)
Clearly would just try to print rtest.
I also know there's
test = 'C:\\Windows\Users\alexb\'
print(repr(test))
But this returns 'C:\\Windows\\Users\x07lexb'
as does
test = 'C:\\Windows\Users\alexb\'
print(test.encode('string-escape'))
So I'm wondering if there's any elegant way to make a variable holding that path print RAW, still using test? It would be nice if it was just
print(raw(test))
But its not
I had a similar problem and stumbled upon this question, and know thanks to Nick Olson-Harris' answer that the solution lies with changing the string.
Two ways of solving it:
Get the path you want using native python functions, e.g.:
test = os.getcwd() # In case the path in question is your current directory
print(repr(test))
This makes it platform independent and it now works with .encode. If this is an option for you, it's the more elegant solution.
If your string is not a path, define it in a way compatible with python strings, in this case by escaping your backslashes:
test = 'C:\\Windows\\Users\\alexb\\'
print(repr(test))
In general, to make a raw string out of a string variable, I use this:
string = "C:\\Windows\Users\alexb"
raw_string = r"{}".format(string)
output:
'C:\\\\Windows\\Users\\alexb'
You can't turn an existing string "raw". The r prefix on literals is understood by the parser; it tells it to ignore escape sequences in the string. However, once a string literal has been parsed, there's no difference between a raw string and a "regular" one. If you have a string that contains a newline, for instance, there's no way to tell at runtime whether that newline came from the escape sequence \n, from a literal newline in a triple-quoted string (perhaps even a raw one!), from calling chr(10), by reading it from a file, or whatever else you might be able to come up with. The actual string object constructed from any of those methods looks the same.
I know i'm too late for the answer but for people reading this I found a much easier way for doing it
myVariable = 'This string is supposed to be raw \'
print(r'%s' %myVariable)
try this. Based on what type of output you want. sometime you may not need single quote around printed string.
test = "qweqwe\n1212as\t121\\2asas"
print(repr(test)) # output: 'qweqwe\n1212as\t121\\2asas'
print( repr(test).strip("'")) # output: qweqwe\n1212as\t121\\2asas
Get rid of the escape characters before storing or manipulating the raw string:
You could change any backslashes of the path '\' to forward slashes '/' before storing them in a variable. The forward slashes don't need to be escaped:
>>> mypath = os.getcwd().replace('\\','/')
>>> os.path.exists(mypath)
True
>>>
Just simply use r'string'. Hope this will help you as I see you haven't got your expected answer yet:
test = 'C:\\Windows\Users\alexb\'
rawtest = r'%s' %test
I have my variable assigned to big complex pattern string for using with re module and it is concatenated with few other strings and in the end I want to print it then copy and check on regex101.com.
But when I print it in the interactive mode I get double slash - '\\w'
as #Jimmynoarms said:
The Solution for python 3x:
print(r'%s' % your_variable_pattern_str)
Your particular string won't work as typed because of the escape characters at the end \", won't allow it to close on the quotation.
Maybe I'm just wrong on that one because I'm still very new to python so if so please correct me but, changing it slightly to adjust for that, the repr() function will do the job of reproducing any string stored in a variable as a raw string.
You can do it two ways:
>>>print("C:\\Windows\Users\alexb\\")
C:\Windows\Users\alexb\
>>>print(r"C:\\Windows\Users\alexb\\")
C:\\Windows\Users\alexb\\
Store it in a variable:
test = "C:\\Windows\Users\alexb\\"
Use repr():
>>>print(repr(test))
'C:\\Windows\Users\alexb\\'
or string replacement with %r
print("%r" %test)
'C:\\Windows\Users\alexb\\'
The string will be reproduced with single quotes though so you would need to strip those off afterwards.
To turn a variable to raw str, just use
rf"{var}"
r is raw and f is f-str; put them together and boom it works.
Replace back-slash with forward-slash using one of the below:
re.sub(r"\", "/", x)
re.sub(r"\", "/", x)
This does the trick
>>> repr(string)[1:-1]
Here is the proof
>>> repr("\n")[1:-1] == r"\n"
True
And it can be easily extrapolated into a function if need be
>>> raw = lambda string: repr(string)[1:-1]
>>> raw("\n")
'\\n'
i wrote a small function.. but works for me
def conv(strng):
k=strng
k=k.replace('\a','\\a')
k=k.replace('\b','\\b')
k=k.replace('\f','\\f')
k=k.replace('\n','\\n')
k=k.replace('\r','\\r')
k=k.replace('\t','\\t')
k=k.replace('\v','\\v')
return k
Here is a straightforward solution.
address = 'C:\Windows\Users\local'
directory ="r'"+ address +"'"
print(directory)
"r'C:\\Windows\\Users\\local'"

python: SyntaxError: EOL while scanning string literal

I have the above-mentioned error in s1="some very long string............"
Does anyone know what I am doing wrong?
You are not putting a " before the end of the line.
Use """ if you want to do this:
""" a very long string ......
....that can span multiple lines
"""
I had this problem - I eventually worked out that the reason was that I'd included \ characters in the string. If you have any of these, "escape" them with \\ and it should work fine.
(Assuming you don't have/want line breaks in your string...)
How long is this string really?
I suspect there is a limit to how long a line read from a file or from the commandline can be, and because the end of the line gets choped off the parser sees something like s1="some very long string.......... (without an ending ") and thus throws a parsing error?
You can split long lines up in multiple lines by escaping linebreaks in your source like this:
s1="some very long string.....\
...\
...."
In my situation, I had \r\n in my single-quoted dictionary strings. I replaced all instances of \r with \\r and \n with \\n and it fixed my issue, properly returning escaped line breaks in the eval'ed dict.
ast.literal_eval(my_str.replace('\r','\\r').replace('\n','\\n'))
.....
I faced a similar problem. I had a string which contained path to a folder in Windows e.g. C:\Users\ The problem is that \ is an escape character and so in order to use it in strings you need to add one more \.
Incorrect: C:\Users\
Correct: C:\\Users\\
You can try this:
s = r'long\annoying\path'
I too had this problem, though there were answers here I want to an important point to this
after
/ there should not be empty spaces.Be Aware of it
I also had this exact error message, for me the problem was fixed by adding an " \"
It turns out that my long string, broken into about eight lines with " \" at the very end, was missing a " \" on one line.
Python IDLE didn't specify a line number that this error was on, but it red-highlighted a totally correct variable assignment statement, throwing me off. The actual misshapen string statement (multiple lines long with " \") was adjacent to the statement being highlighted. Maybe this will help someone else.
In my case, I use Windows so I have to use double quotes instead of single.
C:\Users\Dr. Printer>python -mtimeit -s"a = 0"
100000000 loops, best of 3: 0.011 usec per loop
In my case with Mac OS X, I had the following statement:
model.export_srcpkg(platform, toolchain, 'mymodel_pkg.zip', 'mymodel.dylib’)
I was getting the error:
File "<stdin>", line 1
model.export_srcpkg(platform, toolchain, 'mymodel_pkg.zip', 'mymodel.dylib’)
^
SyntaxError: EOL while scanning string literal
After I change to:
model.export_srcpkg(platform, toolchain, "mymodel_pkg.zip", "mymodel.dylib")
It worked...
David
In my case, I forgot (' or ") at the end of string. E.g 'ABC' or "ABC"
I was getting this error in postgresql function. I had a long SQL which I broke into multiple lines with \ for better readability. However, that was the problem. I removed all and made them in one line to fix the issue. I was using pgadmin III.
Your variable(s1) spans multiple lines. In order to do this (i.e you want your string to span multiple lines), you have to use triple quotes(""").
s1="""some very long
string............"""
In this case, three single quotations or three double quotations both will work!
For example:
"""Parameters:
...Type something.....
.....finishing statement"""
OR
'''Parameters:
...Type something.....
.....finishing statement'''
I had faced the same problem while accessing any hard drive directory.
Then I solved it in this way.
import os
os.startfile("D:\folder_name\file_name") #running shortcut
os.startfile("F:") #accessing directory
The picture above shows an error and resolved output.
All code below was tested with Python 3.8.3
Simplest -- just use triple quotes.
Either single:
long_string = '''some
very
long
string
............'''
or double:
long_string = """some
very
long
string
............"""
Note: triple quoted strings retain indentation, it means that
long_string = """some
very
long
string
............"""
and
long_string = """some
very
long
string
............"""
or even just
long_string = """
some
very
long
string
............"""
are not the same.
There is a textwrap.dedent function in standard library to deal with this, though working with it is out of question's scope.
You can, as well, use \n inside a string, residing on single line:
long_string = "some \nvery \nlong \nstring \n............"
Also, if you don't need any linefeeds (i.e. newlines) in your string, you can use \ inside regular string:
long_string = "some \
very \
long \
string \
............"
Most previous answers are correct and my answer is very similar to aaronasterling, you could also do 3 single quotations
s1='''some very long string............'''

Categories