簡體   English   中英

為什么字符串沒有被寫入臨時文件?

[英]Why is string not being written into tempfile?

我有一個腳本,我在其中創建了一個臨時文件並嘗試在其上寫入一個字符串,然后嘗試在其中運行 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()

這是一個解決方法,以防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一旦關閉就不要刪除它。 然后再次打開閱讀。

在這種情況下,使用簡單的文本寫入和讀取模式是可行的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM