如何执行python脚本并将输出写入txt文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21963270/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to execute a python script and write output to txt file?
提问by user2957951
I'm executing a .py file, which spits out a give string. This command works fine
我正在执行一个 .py 文件,它会输出一个给定的字符串。这个命令工作正常
execfile ('file.py')
execfile ('file.py')
But I want the output (in addition to it being shown in the shell) written into a text file.
但我希望将输出(除了在 shell 中显示之外)写入文本文件。
I tried this, but it's not working :(
我试过这个,但它不起作用:(
execfile ('file.py') > ('output.txt')
execfile ('file.py') > ('output.txt')
All I get is this:
我得到的只是这个:
tugsjs6555
tugsjs6555
False
错误的
I guess "False" is referring to the output file not being successfully written :(
我猜“假”是指未成功写入输出文件:(
Thanks for your help
谢谢你的帮助
采纳答案by Nick Beeuwsaert
what your doing is checking the output of execfile('file.py')against the string 'output.txt'
你所做的是execfile('file.py')根据字符串检查输出'output.txt'
you can do what you want to do with subprocess
你可以用子流程做你想做的事
#!/usr/bin/env python
import subprocess
with open("output.txt", "w+") as output:
subprocess.call(["python", "./script.py"], stdout=output);
回答by aknuds1
This'll also work, due to directing standard out to the file output.txt before executing "file.py":
这也可以工作,因为在执行“file.py”之前将标准输出定向到文件 output.txt:
import sys
orig = sys.stdout
with open("output.txt", "wb") as f:
sys.stdout = f
try:
execfile("file.py", {})
finally:
sys.stdout = orig
Alternatively, execute the script in a subprocess:
或者,在子进程中执行脚本:
import subprocess
with open("output.txt", "wb") as f:
subprocess.check_call(["python", "file.py"], stdout=f)
If you want to write to a directory, assuming you wish to hardcode the directory path:
如果要写入目录,假设您希望对目录路径进行硬编码:
import sys
import os.path
orig = sys.stdout
with open(os.path.join("dir", "output.txt"), "wb") as f:
sys.stdout = f
try:
execfile("file.py", {})
finally:
sys.stdout = orig
回答by Remolten
Use this instead:
改用这个:
text_file = open('output.txt', 'w')
text_file.write('my string i want to put in file')
text_file.close()
Put it into your main file and go ahead and run it. Replace the string in the 2nd line with your string or a variable containing the string you want to output. If you have further questions post below.
把它放到你的主文件中,然后运行它。用您的字符串或包含要输出的字符串的变量替换第二行中的字符串。如果您有其他问题,请在下面留言。
回答by don
file_open = open("test1.txt", "r")
file_output = open("output.txt", "w")
for line in file_open:
print ("%s"%(line), file=file_output)
file_open.close()
file_output.close()
回答by Dibin Joseph
The simplest way to run a script and get the output to a text file is by typing the below in the terminal:
运行脚本并将输出输出到文本文件的最简单方法是在终端中键入以下内容:
PCname:~/Path/WorkFolderName$
python scriptname.py>output.txt
PCname:~/Path/WorkFolderName$
python scriptname.py>output.txt
*Make sure you have created output.txt in the work folder before executing the command.
*在执行命令之前,请确保您已在工作文件夹中创建了 output.txt。
回答by Nitin Upadhyay
using some hints from Remolten in the above posts and some other links I have written the following:
在上面的帖子和其他一些链接中使用来自 Remolten 的一些提示,我写了以下内容:
from os import listdir
from os.path import isfile, join
folderpath = "/Users/nupadhy/Downloads"
filenames = [A for A in listdir(folderpath) if isfile(join(folderpath,A))]
newlistfiles = ("\n".join(filenames))
OuttxtFile = open('listallfiles.txt', 'w')
OuttxtFile.write(newlistfiles)
OuttxtFile.close()
The code above is to list all files in my download folder. It saves the output to the output to listallfiles.txt. If the file is not there it will create and replace it with a new every time to run this code. Only thing you need to be mindful of is that it will create the output file in the folder where your py script is saved. See how you go, hope it helps.
上面的代码是列出我下载文件夹中的所有文件。它将输出保存到 listallfiles.txt 的输出。如果文件不存在,它会在每次运行此代码时创建并用新文件替换它。您唯一需要注意的是,它将在保存 py 脚本的文件夹中创建输出文件。看看你的情况,希望对你有帮助。
回答by Shilpa Amarendrababu Sujatha
If you are running the file on Windows command prompt:
如果您在 Windows 命令提示符下运行该文件:
python filename.py >> textfile.txt
The output would be redirected to the textfile.txt in the same folder where the filename.py file is stored.
输出将被重定向到存储 filename.py 文件的同一文件夹中的 textfile.txt。
The above is only if you have the results showing on cmd and you want to see the entire result without it being truncated.
以上仅当您在 cmd 上显示结果并且您希望看到整个结果而不被截断时。
回答by KowaiiNeko
You could also do this by going to the path of the folder you have the python script saved at with cmd, then do the name.py > filename.txt It worked for me on windows 10
您也可以通过转到使用 cmd 保存 python 脚本的文件夹的路径来执行此操作,然后执行 name.py > filename.txt 它在 Windows 10 上对我有用

