為什么我的代碼沒有保存為原始文本?請解釋。此問題已由投票最多的人回答,謝謝您的建議。
這是我的代碼:
import re
#where I opened the file
file = open("old.txt")
story = file.readlines()
#Attempt to save file under new name with same format as orginal.
new = open('anotherstory.txt' , 'w')
new.write()
new.close()
# Made the substitution for the name
name = 'heatherly'
subname = 'joe'
nameCount = re.findall(name)
found = re.replace(name, subname)
uj5u.com熱心網友回復:
使用 時,您正在對串列的字串表示進行操作str(story),因為.readlines()回傳字串串列。
快速修復是替換.readlines()為.read()(以一個連續的字串而不是每個代表一行的字串串列獲取檔案的內容)。
話雖如此,我認為我們可以做得更好。您可以在此處消除兩個不必要的復雜性:
- 通常,對檔案使用背景關系管理器(
with陳述句)——這些管理器會自動為您關閉檔案。 - 您不需要正則運算式:
.replace()在這里可以進行簡單的字串操作。
有了這個,我們得到:
with open("story.txt") as input_file, open("anotherstory.txt", "w") as output_file:
for line in input_file:
output_file.write(line.replace('heatherly', 'joe'))
uj5u.com熱心網友回復:
更改此行
story = file.readlines()
和
story = file.read()
uj5u.com熱心網友回復:
str(story)將行串列格式化為
['line1', 'line2', 'line3', ...]`
這不是您想要的檔案格式。
您應該將檔案作為單個字串讀取,而不是行串列。那你就不需要打電話了str(story)。
也沒有必要使用re.sub(),因為name它不是正則運算式。
#where I opened the file
with open("story.txt") as file:
story = file.read()
# Made the substitution for the name
name = 'heatherly'
subname = 'joe'
nameCount = story.count(name)
found = story.replace(name, subname)
#Attempt to save file under new name with same format as orginal.
with open('anotherstory.txt' , 'w') as new:
new.write(found)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/454730.html
