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

Time:09-17

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!

CodePudding user response:

Use shlex.quote()

import shlex

cd = r"printf '%s\n' {} >> t.dat".format(shlex.quote(f.read()))
  • Related