Python string corrupted with character \

0

I have a program that creates another program on the user's computer. In a snippet, I define the directory to which the new program will be destined as

 diret = "C:\Users\" + d_user

where d_user is the rest of the directory. However when it is created and executed, the string is converted to

'C:\Users\' 

with a bar only, which raises

SyntaxError: EOL while scanning string literal 

because the string is not closed in the second ['].

How can I prevent this from occurring in order for my code to be fully executed?

EDIT:

The code within the master code, which will be created, is available at link from lines 4 through 24; the rest are just the context of the main code. The error happens with line 10.

    
asked by anonymous 11.04.2018 / 02:49

1 answer

2

The line

diret = "C:\Users\" + d_user

is correct. What happens is that \ is an escape character; that is, when you need to, for example, use quotation marks without finishing the string, you can do

s = "aspas: \" <- interpretado como aspas sem fechar a string"

Thus, it is interpreted in a special way and it also needs to be escaped with \ . When you want to put a character \ in the string, you must use \ (the first "escapes" the second and the second is interpreted literally).

What you write in a new file is escaped, but therefore results in writing only a \ at a time. When the second file is read, there is only \ and it escapes the double quotation marks at the end of the string.

To solve your problem, there are two possible solutions. The first is to double the bars in key_file.write :

...
diret = "C:\\Users\\" + d_user
...

And the second and perhaps more elegant is to use a raw string, or raw, prefixing it with r . Thus, \ is treated as a normal character.

key_file.write(r'''
    import sys
    [...]
    input()''')
    
11.04.2018 / 03:41