English 中文(简体)
将印刷产出引向txt文档
原标题:Directing print output to a .txt file

是否有办法将全部印刷产出节省到金字塔档案中? 请允许我说,我有这两条文字,我希望将印刷产出节省到一个名为<编码>产出.txt的文件。

print ("Hello stackoverflow!")
print ("I have a question.")

I want the output.txt file to to contain

Hello stackoverflow!
I have a question.
最佳回答

www.un.org/spanish/ga/president 最佳做法是使用<条码>的<条码/代码>栏号打开<>开放式功能的文档,以确保文件在栏目末关闭:

with open("output.txt", "a") as f:
  print("Hello stackoverflow!", file=f)
  print("I have a question.", file=f)

http://docs.python.org/3.5/library/Functions.html#print”rel=“noreferer” 关于<代码>的灰色文件:

file case must be an Object with a write(string) means; if it is not present or None,sys.stdout will be used.

And the documentation for open:

开放式<编码>file,并交还相应的文档标。 如果档案不能开启,则提出OSError

The "a" as the second argument of open means "append" - in other words, the existing contents of the file won t be overwritten. If you want the file to be overwritten instead at the beginning of the with block, use "w".


《<<>代码>和栏目是有用的,因为否则,你需要记住,如:

f = open("output.txt", "a")
print("Hello stackoverflow!", file=f)
print("I have a question.", file=f)
f.close()
问题回答

你们可以把 st改成“产出.txt”档案:

import sys
sys.stdout = open( output.txt , wt )
print ("Hello stackoverflow!")
print ("I have a question.")

另一种无需更新甲型六氯环己烷法的方法是通过 con/strong>。

基本上,你的字母<代码>(>>(>)与往常一样,把文字从指挥线上说出来,并使用指挥线重新定向。 与此类似:

$ python ./myscript.py > output.txt

页: 1

Edit:
To address the comment; for Windows, change the forward-slash to a backslash.
(i.e. .myscript.py)

伐木模块的使用

def init_logging():
    rootLogger = logging.getLogger( my_logger )

    LOG_DIR = os.getcwd() +  /  +  logs 
    if not os.path.exists(LOG_DIR):
        os.makedirs(LOG_DIR)
    fileHandler = logging.FileHandler("{0}/{1}.log".format(LOG_DIR, "g2"))
    rootLogger.addHandler(fileHandler)

    rootLogger.setLevel(logging.DEBUG)

    consoleHandler = logging.StreamHandler()
    rootLogger.addHandler(consoleHandler)

    return rootLogger

2. 结 论:

logger = init_logging()

开始伐木/产出:

logger.debug( Hi! :) )

另一种变式可以是...... 之后,确保结案

import sys
file = open( output.txt ,  a )
sys.stdout = file

print("Hello stackoverflow!") 
print("I have a question.")

file.close()

保证进口sys模块。 印刷你们想要书写和想要挽救的东西。 在sys模块中,我们有stdout,该模块接收产出和储存。 然后,sys.stdout。 这将节省产出。

import sys
# Save a reference to sys.stdout file object
stdout = sys.stdout

print("Hello stackoverflow!" 
      "I have a question.")

file = open("/home/scilab/Desktop/test.txt", "a")
sys.stdout = file
# main code ...

# Restore stdout to the sys.stdout file object you saved
# This prevents stdout from erroring out on a closed file     # object
sys.stdout = stdout
# Don t close stdout directly
file.close()

我的投入文件是“投入.txt”,产出文件是“产出.txt”。

让我们考虑投入文件的细节如下:

5
1 2 3 4 5

法典:

import sys

sys.stdin = open("input", "r")
sys.stdout = open("output", "w")

print("Reading from input File : ")
n = int(input())
print("Value of n is :", n)

arr = list(map(int, input().split()))
print(arr)

因此,从投入文件来看,产出将在产出档案中显示。

详情请见

a. 添加阴.的回答;为了让 p重新印制到 con子,而不是你必须做的档案:

import sys
list = [10,20,30,40,50]

with open( output.txt ,  w ) as f:
    old_stdout = sys.stdout
    sys.stdout = f
    print(list)
    sys.stdout = old_stdout

PS: All credit to https://www.datasciencelearner.com/get-python-output-in-text-file/。 - 即发现信息。 (我作出这一答复是因为我没有声誉来评论先前的答复。)

Edit:我编辑了该守则,以使用一个变量储存<代码>sys.stdout的旧价值,然后重新命名;而不是使用<代码>sys.__stdout_;因为前者在上讨论更为安全。





相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...