我正在嘗試撰寫一個程式來讀取檔案 a.txt 中的輸入
Hi this is nick, I am male and I am 30 years old.
并替換人的姓名、年齡和性別,并將其寫入新檔案b.txt。下面是我的嘗試。
orig_file=open("a.txt","r") # file handle
new_file=open("b.txt","w") # new file handle
temp_buffer=orig_file.read()
lookup_dict={"nick":"andrea", "male":"female", "30":"20"}
for line in temp_buffer:
for word in lookup_dict:
line= line.replace(word, lookup_dict[word])
new_file.write(line)
我對 b.txt 的預期結果是
Hi this is andrea, I am female and I am 20 years old.
觀察到的輸出 (b.txt)
HHHiii ttthhhiiisss iiisss nnniiiccckkk,,, III aaammm mmmaaallleee aaannnddd III aaammm 333000 yyyeeeaaarrrsss ooolllddd...
有人可以解釋我做錯了什么并糾正我。
uj5u.com熱心網友回復:
使用readlines代替read并close()手動呼叫檔案,因為您沒有使用with:
orig_file = open("a.txt", "r") # file handle
new_file = open("b.txt", "w") # new file handle
temp_buffer = orig_file.readlines()
orig_file.close()
lookup_dict = {"nick": "andrea", "male": "female", "30": "20"}
for line in temp_buffer:
for word in lookup_dict:
line = line.replace(word, lookup_dict[word])
new_file.write(line)
new_file.close()
b.txt:
Hi this is andrea, I am female and I am 20 years old.
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/386376.html
