echo multiple lines (from another file) with multiple quotes/special characters into a new file?

I have a python script which opens a file and reads it:

f= open("/file.dat", "r").read()

file.dat is a multiple lines file with quotes, spaces, new lines and special characters such as #,&,"

I would like to echo f into a new file named t.dat. I have tried:

cd= "echo "{}" >> t.dat".format(f)
os.system(cd)

which prints to the screen the file content until the “& config” which is in it and the error: sh: 32: Config: not found

Tried the following as well with similar results:

cd= "$echo "{}" >> t.dat".format(f)
cd= "$echo {} >> t.dat".format(f)

What is the correct way to perform this? Thank you!

Answer

Use shlex.quote()

import shlex

cd = r"printf '%sn' {} >> t.dat".format(shlex.quote(f.read()))