Python String corrupted with character \

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

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

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

'C:\Users\' 

With one 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 happening in order for my code run fully?

EDIT:

The code within the main code, which will be created, is available at https://ideone.com/KTAQxf from lines 4 to 24; the rest are just Main Code context. The error happens with Line 10.

Author: William, 2018-04-11

1 answers

The line

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

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

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

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

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

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

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

And the second and perhaps most 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()''')
 4
Author: Pedro von Hertwig Batista, 2018-04-11 01:41:29