Python 3 print() 到变量

标签 python python-3.x printing

在 Python 3 中,您可以使用 print 函数将数据写入文件(例如 print('my data', file=my_open_file)。这很好(而且非常酷) )。但是你可以打印到一个(字符串?)变量吗?如果可以,怎么做?

在我的特定用例中,我试图避免将数据写入磁盘上的临时文件只是为了打开和读取该临时文件。

编辑:我不能只是分配,因为我的源数据不是字符串,而是由 BeautifulSoup 提取的 html 文档树的一部分。提取文档树后,我将逐行处理它。

<小时/>

我的代码:(正在工作!)

with open("index.html", "r") as soup_file:
    soup = BeautifulSoup(soup_file)
THE_BODY = soup.find('body')
not_file = io.StringIO()
print(THE_BODY, file = not_file)    # dump the contents of the <body> tag into a file-like stream
with codecs.open('header.js', "w", "utf-8") as HEADER_JS:
    for line in not_file2.getvalue().split('\n'):
        print("headerblock += '{}'".format(line), file = HEADER_JS)
<小时/>

更好、有效的代码:

with open("index.html", "r") as soup_file:
    soup = BeautifulSoup(soup_file)
with codecs.open('header.js', "w", "utf-8") as HEADER_JS:
    for line in str(soup.find('body')).split('\n'):
        print("headerblock += '{}'".format(line), file = HEADER_JS)

最佳答案

根据更新的问题更新的回复

如果您需要做的只是将对象转换为字符串,只需对变量调用 str 函数...这就是 print 内部所做的事情。

a = str(soup.find('body'))

如果您需要的只是字符串表示形式,则调用 print 会执行一大堆您不需要的其他操作。

<小时/>

原始回复

您可以使用io.StringIO

import io 
f = io.StringIO()
print('my data', file=f)

# to get the value back
a = f.getvalue()
print(a)
f.close()

请注意,在 python2 上,它位于 StringIO.StringIO 下。

当您有预先存在的代码想要打印到文件,但您更愿意在变量中捕获该输出时,此解决方案非常有用。

关于Python 3 print() 到变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27137938/

相关文章:

HTML 页眉/页脚打印功能

firefox - 在 Firefox 中打印网页字体

python - 从 Axes(或Figure)获取 QuadMesh 对象

python - 有人可以举一个 "operator.index ()"的例子吗?

带有 sys.argv[] 的 Python 3.x 调用函数

c# - protobuf 包是如何使用的?

python - 循环每个元素并根据该元素打印 word2vec 向量

python - 使用 python 打印最近 20 个 bash 历史记录并保存在 pdf 文件中

python - 由于 : file does not start with RIFF id,无法将文件 file.wav 作为 WAV 打开

python - 打印语句的记录模块 : Duplicate log entries