Home > Net >  How can I print "\n" using exec()?
How can I print "\n" using exec()?

Time:05-31

ab = open("bonj.txt","w")

exec(f'''print("Hi I'm Mark\n", file=ab)
print("\tToday I'm tired", file=ab)
''')

ab.close()

I would absolutely need to use exec() to print some informations on a txt doc. The problem is that when I use exec(), I lost the possibility of put newlines or tabs on my text, and I dont understand why, could you help me ?

This is the error message that I receive : "SyntaxError: EOL while scanning string literal"

CodePudding user response:

You just need to escape \n and \t properly

ab = open("bonj.txt","w")

exec(f'''print("Hi I'm Mark\\n", file=ab)
print("\\tToday I'm tired", file=ab)
''')

ab.close()

CodePudding user response:

You need to prevent python from interpreting the \n early.

This can be done by specifying the string as a raw string, using the r prefix:

ab = open("bonj.txt","w")
exec(rf'''print("Hi I'm Mark\n", file=ab)
print("\tToday I'm tired", file=ab)
''')
ab.close()

Anyway, using exec is odd there, you would rather try to see if you can write your code as something like:

lines = ["Hi I'm Mark\n", "\tToday I'm tired"]
with open("bonj.txt", "w") as f:                                                                                                                                                                                 
    f.write("\n".join(lines))

Note that you need to use "\n".join to obtain the same result as with print because print adds a newline by default (see its end="\n" argument).

Also, when handling files, using the context manager syntax (with open ...) is good practice.

  • Related