【发布时间】:2016-09-08 04:31:57
【问题描述】:
我是编程初学者。 我必须在python中运行一个程序并将输出保存在一个具体的文件夹中,但是所有的输出都保存在我的家中,谁能告诉我如何选择目录?
我使用了这个命令:
commands.getstatusoutput(cmd)
提前致谢
【问题讨论】:
-
请发布您尝试过的代码。这将有助于回答! :)
标签: python directory command output
我是编程初学者。 我必须在python中运行一个程序并将输出保存在一个具体的文件夹中,但是所有的输出都保存在我的家中,谁能告诉我如何选择目录?
我使用了这个命令:
commands.getstatusoutput(cmd)
提前致谢
【问题讨论】:
标签: python directory command output
我假设您想知道如何选择 WHERE 可以写入文件。假设您已经将想要的输出保存在一个变量中:
my_output_text = "Some interesting text"
通常,您应该将输出写入您的程序具有写入权限的位置。因为你对你的主目录有完全的写访问权,这可能就是它当前指向那里的原因。您还可以在大多数基于 *nix 的系统上使用像 /tmp/ 这样的临时目录。只需像这样为该文件创建一个变量:
my_preferred_output_file = '/tmp/my_output.txt' # this can be anywhere your program has write-access to
然后编写保存到它的代码。一种快速的方法是使用with 上下文管理器:
with open(my_preferred_output_file, 'w') as outfile:
outfile.write(my_output_text)
另一种方法是使用日志记录。
import logging
logging.basicConfig(filemode='w', filename=my_preferred_output_file, level=logging.INFO)
log = logging.getLogger('output_log') # this just names your logger
log.info(my_output_text)
请参阅https://docs.python.org/3/tutorial/inputoutput.html 了解更多信息。
【讨论】: