在 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/