简体   繁体   中英

Redirecting output to file in python

In shell script if we have sth like :

field1 = 22
qry="delete from table_name where id = $field1
echo $qry >> /tmp/query.ksh

Here in the file we have

delete from table_name where id = 22

I want to achieve the same in python

How should I achieve this in python I am doing

fo = open("file","a")
fo.write(qry)

But this is not working.

Please suggest the correct way.

Something like what you already have should work fine.

   field1 = 22
   qry = "delete from table_name where id = {0}\n".format(field1)
   with open('your_file', 'a') as f:
     f.write(qry)

what is specifically not working? where is all your python code? you posted only 2 lines where are you defining qry ?

The code you show is correct assuming you want to append to a file named file .

Note that you should close the files that you open or (on recent Python versions) use with statements. Translating your shell code to Python,

field1 = 22
qry = "delete from table_name where id = {}".format(field1)
with open('/tmp/query.ksh', 'a') as of:
    of.write(qry)

Note that in real life you should not directly insert data into prepared SQL statements, because it can possibly lead to SQL injections.

Your code is working, alternatively you can direct print output to file by doing this:

import sys
sys.stdout = open("file","a")

field1 = 22
qry = "delete from table_name where id = {0}\n".format(field1)
print qry

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM