简体   繁体   English

将输出重定向到python中的文件

[英]Redirecting output to file in python

In shell script if we have sth like :在 shell 脚本中,如果我们有类似的东西:

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我想在 python 中实现同样的目标

How should I achieve this in python I am doing我应该如何在我正在做的python中实现这一点

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?你所有的python代码在哪里? you posted only 2 lines where are you defining qry ?你只发布了 2 行你在哪里定义qry

The code you show is correct assuming you want to append to a file named file .假设您要附加到名为file的文件,您显示的代码是正确的。

Note that you should close the files that you open or (on recent Python versions) use with statements.请注意,您应该关闭您打开的文件或(在最近的 Python 版本上)使用with语句的文件。 Translating your shell code to Python,将你的 shell 代码翻译成 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.请注意,在现实生活中,您不应该直接将数据插入到准备好的 SQL 语句中,因为这可能会导致 SQL 注入。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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