반응형
파이썬 인쇄 문자열을 텍스트 파일로
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
반응형
'your programing' 카테고리의 다른 글
Redux에서 비동기 흐름을 위해 미들웨어가 필요한 이유는 무엇입니까? (0) | 2020.10.03 |
---|---|
C #에서 파일 이름 바꾸기 (0) | 2020.10.03 |
C #에서 문자열을 바이트 배열로 변환 (0) | 2020.10.03 |
잡아 당긴 텍스트를 Vim 명령 줄에 붙여 넣는 방법은 무엇입니까? (0) | 2020.10.03 |
rm, cp, mv 명령에 대한 인수 목록이 너무 김 오류 (0) | 2020.10.03 |