我有一個腳本,我在其中創建了一個臨時檔案并嘗試在其上寫入一個字串,然后嘗試在其中運行 for 回圈(而“with”方法是“活動的”)。
在 for 回圈中,我嘗試根據預定義的模式附加特定的行,但是當我在附加行后列印串列時,不僅 lsist 顯示為空,而且 Division_text 字串未在臨時檔案中注冊開始。
我基本上是將字串寫入臨時檔案并同時讀取它。也許這就是問題所在。
因此,最后的 3 個列印(每個串列一個)顯示為空。
為什么字串沒有列印到臨時檔案中?
import tempfile
division_text = 'Hello, world.'
my_list = []
keywords = ['Hello']
pattern = re.compile('|'.join(keywords))
# create temporary .txt file to store string output from web scrape (division_text)
with tempfile.NamedTemporaryFile() as tmp:
print(tmp.name)
tmp.write(bytes(division_text, encoding='utf8')) # division_text is a string variable with many lines of text
for line in tmp:
print(line)
if re.search(pattern, line):
my_list.append(line)
print(len(token_amount)) # []
如果我tmp.writelines()改用,它會給我以下錯誤:
TypeError: a bytes-like object is required, not 'int'
如果我使用NamedTemporaryFile(mode='w'),而是和使用tmp.write(division_text),它給了我下面的錯誤:io.UnsupportedOperation: not readable。
我在嘗試時遇到同樣的錯誤:
with tempfile.NamedTemporaryFile(mode = 'r ') as tmp:
print(tmp.name)
tmp.write(division_text)
tmp.seek(0)
tmp.read()
uj5u.com熱心網友回復:
這是一種解決方法,以防r 模式導致問題(此處沒有問題,但可能取決于系統)
import tempfile,os
division_text = "12.0"
# create a temporary file, don't delete it when done
tmp_file = tempfile.NamedTemporaryFile(mode = 'w',delete=False)
with tmp_file as tmp:
print(tmp.name)
tmp.write(division_text)
# reopen the file for reading
with open(tmp_file.name) as tmp:
new_division_text=tmp.read()
# remove the file manually
os.remove(tmp_file.name)
# print result
print(new_division)
這個想法是創建臨時檔案,但告訴python一旦關閉就不要洗掉它。然后再次打開閱讀。
在這種情況下,使用簡單的文本寫入和讀取模式是可行的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/314384.html
