如何将控制台中的多个段落写入文件Python

2024-06-16 09:29:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一行代码打印出这样一段:

print("An Apple a day keeps the doctor away ... ") #paragraph1
.
.
.
print("Two Apples a day keeps two doctors away ... ") #paragraph2
.
.
.
json.dump(someData) #paragraph3

我只想将控制台中打印的所有段落都指向一个文件。在

注:

有什么功能可以实现这一点吗?(将控制台中打印的所有段落一次性写入一个文件?)在


Tags: 文件theto代码anapple段落print
2条回答

尝试将段落存储到字符串变量中。看起来像这样

p1 = "An Apple a day keeps the doctor away ... "
p2 = "Two Apples a day keeps two doctor away ... "

print(p1)
print(p2)

with open("output.txt", "w")as output:
    p1and2 = p1 + p2
    output.write(p1and2)

希望这个有用

将stdout转移到文件

import sys
sys.stdout = open('file', 'w')
print 'hello'

相关问题 更多 >