your programing

파이썬 인쇄 문자열을 텍스트 파일로

lovepro 2020. 10. 3. 11:25
반응형

파이썬 인쇄 문자열을 텍스트 파일로


Python을 사용하여 텍스트 문서를 엽니 다.

text_file = open("Output.txt", "w")

text_file.write("Purchase Amount: " 'TotalAmount')

text_file.close()

문자열 변수의 값을 TotalAmount텍스트 문서로 대체하고 싶습니다 . 누군가이 방법을 알려주시겠습니까?


text_file = open("Output.txt", "w")
text_file.write("Purchase Amount: %s" % TotalAmount)
text_file.close()

컨텍스트 관리자를 사용하는 경우 파일이 자동으로 닫힙니다.

with open("Output.txt", "w") as text_file:
    text_file.write("Purchase Amount: %s" % TotalAmount)

Python2.6 이상을 사용하는 경우 다음을 사용하는 것이 좋습니다. str.format()

with open("Output.txt", "w") as text_file:
    text_file.write("Purchase Amount: {0}".format(TotalAmount))

python2.7 이상에서는 {}대신 사용할 수 있습니다.{0}

Python3 file에는 print함수에 대한 선택적 매개 변수가 있습니다.

with open("Output.txt", "w") as text_file:
    print("Purchase Amount: {}".format(TotalAmount), file=text_file)

Python3.6 은 다른 대안을 위해 f- 문자열도입했습니다.

with open("Output.txt", "w") as text_file:
    print(f"Purchase Amount: {TotalAmount}", file=text_file)

여러 인수를 전달하려는 경우 튜플을 사용할 수 있습니다.

price = 33.3
with open("Output.txt", "w") as text_file:
    text_file.write("Purchase Amount: %s price %f" % (TotalAmount, price))

추가 : 파이썬에서 여러 인수 인쇄


Python3을 사용하는 경우.

그런 다음 인쇄 기능을 사용할 수 있습니다 .

your_data = {"Purchase Amount": 'TotalAmount'}
print(your_data,  file=open('D:\log.txt', 'w'))

python2의 경우

이것은 Python Print String To Text File의 예입니다.

def my_func():
    """
    this function return some value
    :return:
    """
    return 25.256


def write_file(data):
    """
    this function write data to file
    :param data:
    :return:
    """
    file_name = r'D:\log.txt'
    with open(file_name, 'w') as x_file:
        x_file.write('{} TotalAmount'.format(data))


def run():
    data = my_func()
    write_file(data)


run()

numpy를 사용하는 경우 한 줄로 단일 (또는 곱하기) 문자열을 파일에 인쇄 할 수 있습니다.

numpy.savetxt('Output.txt', ["Purchase Amount: %s" % TotalAmount], fmt='%s')

pathlib 모듈을 사용하면 들여 쓰기가 필요하지 않습니다.

import pathlib
pathlib.Path("output.txt").write_text("Purchase Amount: {}" .format(TotalAmount))

파이썬 3.6부터 f- 문자열을 사용할 수 있습니다.

pathlib.Path("output.txt").write_text(f"Purchase Amount: {TotalAmount}")

참고 URL : https://stackoverflow.com/questions/5214578/python-print-string-to-text-file

반응형