在Python 3中,您可以使用 print 函数将数据写入文件(例如print('my data', file=my_open_file)
。这很好(而且非常酷)。但你可以吗print
到(字符串?)变量?如果是这样,怎么办?
在我的特定用例中,我试图避免将数据写入磁盘上的临时文件只是为了打开和读取该临时文件。
Edit:我不能只是分配,因为我的源数据不是字符串,而是由 BeautifulSoup 提取的 html 文档树的一部分。提取文档树后,我将逐行处理它。
My Code:(现在正在工作!)
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)