我有一些代码可以使用print函数的一些功能将内容打印到控制台,例如
print('name'.ljust(44), 'age'.rjust(4), 'idea'.rjust(8), sep=',')
for name, age, idea in items:
print(name.ljust(44), str(age).rjust(4), idea.rjust(8), sep=',')在其他情况下,我将使用end参数将多个字符串写入一行,即
print('hello ', end='')
print('world!')我的问题是,如何才能最容易地将这种print格式的输出写入流、文件,或者更好地只是将其收集到单个字符串对象中?如果我恢复到常规的字符串格式,语法将会不同,并且我将需要重写所有的格式。
发布于 2019-03-05 23:56:46
StringIO允许您像使用文件一样使用字符串。除了使用print(..., file=...),您还可以执行以下操作:
import io
with io.StringIO() as fp:
print("hi", "mom", sep=" ", file=fp)
print('hello ', end='', file=fp)
print('world!', file=fp)
str = fp.getvalue()
print(str)这给了我们
hi mom
hello world!正如(我认为)你所希望的那样。如果您想要每行的字符串列表,也可以使用fp.readlines()。
您还可以使用可能使用文件系统(但可能不使用)的tempfile,其语法几乎相同:
import tempfile
with tempfile.TemporaryFile(mode="w+") as fp:
print("hi", "mom", sep=" ", file=fp)
print('hello ', end='', file=fp)
print('world!', file=fp)
fp.seek(0)
str = fp.read()
print(str)您确实需要指定mode,因为默认情况下会给出一个不允许print的二进制文件,并在读取之前显式地倒回到开头。(FWIW,我答案的早期版本对每个print都有flush=True,但我不认为这是必要的。)
发布于 2019-03-05 23:44:44
泡菜对你有帮助吗?
就像这样
import pickle
text = "Hallo welt Test."
with open('parrot.pkl', 'wb') as f:
pickle.dump(text, f)
with open('parrot.pkl', 'rb') as f:
print(pickle.load(f))https://stackoverflow.com/questions/55006357
复制相似问题