sourcetip

인쇄 출력을 .txt 파일로 지정

fileupload 2023. 5. 28. 21:00
반응형

인쇄 출력을 .txt 파일로 지정

모든 인쇄 출력을 파이썬의 txt 파일에 저장할 수 있는 방법이 있습니까?코드에 이 두 줄이 있고 인쇄 출력을 이름이 지정된 파일에 저장하려고 합니다.output.txt.

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

나는 그것을 원합니다.output.txt포함할 파일

Hello stackoverflow!
I have a question.

print a file키워드 인수. 여기서 인수 값은 파일 스트림입니다.가장 좋은 방법은 파일을 여는 것입니다.open를 사용하여 기능with블록의 끝에서 파일이 닫히도록 합니다.

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

다음에 대한 Python 문서:

file인수는 다음 값을 가진 개체여야 합니다.write(string)방법; 존재하지 않는 경우 또는None,sys.stdout사용됩니다.

다음에 대한 설명서:

열다.file해당 파일 개체를 반환합니다.파일을 열 수 없는 경우OSError상승했습니다.

"a"의 두 번째 주장으로서open즉, 파일의 기존 내용을 덮어쓰지 않습니다.파일을 처음에 대신 덮어쓰려면with블록, 사용"w".


with블록은 유용합니다. 그렇지 않으면 다음과 같이 파일을 직접 닫아야 합니다.

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

stdout을 "output" 파일로 리디렉션할 수 있습니다.txt":

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

Python 코드를 업데이트할 필요가 없는 또 다른 방법은 콘솔을 통해 리디렉션하는 것입니다.

기본적으로 Python 스크립트가 있어야 합니다.print()그런 다음 명령줄에서 스크립트를 호출하고 명령줄 리디렉션을 사용합니다.다음과 같이:

$ python ./myscript.py > output.txt

당신의.output.txt이제 파일에 Python 스크립트의 모든 출력이 포함됩니다.

편집:
주석을 처리하려면 Windows의 경우 슬래시를 백슬래시로 변경합니다.
(즉,.\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

로거 가져오기:

logger = init_logging()

로깅/출력(ing)

logger.debug('Hi! :)')

다른 변형은 다음과 같습니다.나중에 파일을 닫아야 합니다.

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

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

file.close()

입력 파일이 "input.txt"이고 출력 파일이 "output.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)

따라서 이것은 입력 파일에서 읽히고 출력은 출력 파일에 표시됩니다.

자세한 내용은 https://www.geeksforgeeks.org/inputoutput-external-file-cc-java-python-competitive-programming/ 을 참조하십시오.

sys module을 가져와야 합니다. 쓰고 싶은 것과 저장하고 싶은 것을 인쇄하세요.시스템 모듈에는 출력을 가져와서 저장하는 stdout이 있습니다.그런 다음 sys.stdout을 닫습니다.이렇게 하면 출력이 저장됩니다.

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

sys.stdout = open("/home/scilab/Desktop/test.txt", "a")
sys.stdout.close()

Python 3.4 이후에는 redirect_stdout이 있습니다.

import contextlib

with open('output.txt', 'w') as f, contextlib.redirect_stdout(f):
    print("Hello stackoverflow!")
    print("I have a question.")

반환된 함수의 출력을 파일에 직접 추가할 수 있습니다.

print(output statement, file=open("filename", "a"))

언급URL : https://stackoverflow.com/questions/36571560/directing-print-output-to-a-txt-file

반응형