簡體   English   中英

如何執行python腳本並將輸出寫入txt文件?

[英]How to execute a python script and write output to txt file?

我正在執行.py文件,它會吐出一個給定的字符串。 這個命令工作正常

execfile('file.py')

但我希望將輸出(除了它顯示在shell中)寫入文本文件。

我試過這個,但它不起作用:(

execfile('file.py')>('output.txt')

我得到的就是:

tugsjs6555

我猜“False”是指未成功寫入的輸出文件:(

謝謝你的幫助

你正在做的是檢查execfile('file.py')的輸出對字符串'output.txt'

你可以做你想做的子進程

#!/usr/bin/env python
import subprocess
with open("output.txt", "w+") as output:
    subprocess.call(["python", "./script.py"], stdout=output);

這也是有效的,因為在執行“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

或者,在子進程中執行腳本:

import subprocess

with open("output.txt", "wb") as f:
    subprocess.check_call(["python", "file.py"], stdout=f)

如果要寫入目錄,假設您希望對目錄路徑進行硬編碼:

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

請改用:

text_file = open('output.txt', 'w')
text_file.write('my string i want to put in file')
text_file.close()

將它放入主文件中並繼續運行。 用您的字符串或包含您要輸出的字符串的變量替換第二行中的字符串。 如果您在下面有其他問題。

運行腳本並將輸出輸出到文本文件的最簡單方法是在終端中鍵入以下內容:

PCname:〜/ Path / WorkFolderName $ python scriptname.py>output.txt

*確保在執行命令之前在工作文件夾中創建了output.txt。

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()

在上面的帖子和其他一些鏈接中使用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()

上面的代碼是列出我的下載文件夾中的所有文件。 它將輸出保存到listallfiles.txt的輸出。 如果文件不在那里,它將每次創建並用新的替換它來運行此代碼。 您唯一需要注意的是它將在保存py腳本的文件夾中創建輸出文件。 看看你怎么走,希望它有所幫助。

如果您在Windows命令提示符下運行該文件:

python filename.py >> textfile.txt

輸出將重定向到存儲filename.py文件的同一文件夾中的textfile.txt。

只有在cmd上顯示結果並且您希望在不截斷的情況下查看整個結果時,才會出現上述情況。

您也可以通過轉到使用cmd保存python腳本的文件夾的路徑來執行此操作,然后執行name.py> filename.txt它在Windows 10上為我工作

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM