這個問題在這里已經有了答案: 將行寫入檔案的正確方法? (16 個答案) 昨天關門。
我正在處理一個需要匯入文本檔案、清理資料并寫入新文本檔案的專案。我需要最后一步的幫助。我的 Python 程式如下所示:
import re
with open("data.txt") as file:
for line in file:
search_result = re.search(r"^(An act (?:. ?)\.)", line)
if search_result:
print(search_result.group(1))
這成功地根據需要清理文本并列印它。您將如何修改它以寫入 .txt 檔案?謝謝!
uj5u.com熱心網友回復:
您可以進行一些簡單的修改,首先當然是知道如何打開要寫入的檔案,那就是簡單地傳遞第二個可選引數“w”
第一個也是簡單的選擇是將期望結果保存到串列中,完成后將這些結果寫入檔案
示例 1
import re
search_results = []
with open("data.txt") as file:
for line in file:
search_result = re.search(r"^(An act (?:. ?)\.)", line)
if search_result:
result = search_result.group(1)
print(result)
search_results.append(result)
with open("clean data.txt","w") as output_file:
for r in search_results:
output_file.write(r)
output_file.write("\n") # don't forget to put the new line, write doesn't do it for you
但是如果我們可以列印到檔案中呢?這樣我們就不需要記住換行了,好訊息是我們可以,print可以只接受一個關鍵字引數file
,也就是說,我們想要列印輸出的檔案進入
示例 2
import re
search_results = []
with open("data.txt") as file:
for line in file:
search_result = re.search(r"^(An act (?:. ?)\.)", line)
if search_result:
result = search_result.group(1)
print(result)
search_results.append(result)
with open("clean data.txt","w") as output_file:
for r in search_results:
print(r, file=output_file)
但是如果我們這樣做,為什么不按照之前的列印來做呢?答案是:是的,我們可以,假設我們已經完成了對那條資料的處理,我們可以將它直接放入結果檔案中(否則像前面的例子一樣)
示例 3
import re
with open("data.txt") as file, open("clean data.txt","w") as outfile:
for line in file:
search_result = re.search(r"^(An act (?:. ?)\.)", line)
if search_result:
result = search_result.group(1)
print(result)
print(result, file=outfile)
這是最終的形式,該with
陳述句可以同時包含許多東西,我們使用print
了額外的潛力。
下一步是把它或部分放到一個函式中,這樣它就可以更容易地用于更多的檔案,但我把它留給讀者作為練習。
uj5u.com熱心網友回復:
您將搜索結果附加到串列中,打開一個新文本檔案并將其傳遞給您的串列,然后再寫入檔案,如下所示..
import re
search_results = []
with open("data.txt") as file:
for line in file:
search_result = re.search(r"^(An act (?:. ?)\.)", line)
if search_result:
search_results.append(search_result.group(1))
with open('newfile.txt', mode='wt', encoding='utf-8') as myfile:
myfile.write('\n'.join(search_results))
uj5u.com熱心網友回復:
我會將結果添加到一個字串中,用換行符分隔行,而不僅僅是列印。
然后我會以與上面類似的方式打開一個新的文本檔案,但這次是撰寫。(提示:open() 函式還有其他可選引數)
uj5u.com熱心網友回復:
要在 python 中編輯罰款,您必須先使用以下命令打開它:
with open("file.txt", "w") as f:
重要的引數是“w”,表示模式:寫。
然后編輯它你可以這樣做:
f.write("test")
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/493599.html