2017-05-23 84 views
1

嗨,我試圖刪除我的文件中的一行,但想保留我的其餘行。刪除文件的特​​定行

f = open("myfile.html").read() 
lines = f.readlines() 
a = findall('<h2>\$.*', f) 
f.close() 
f = open("myfile.html","w") 
for line in lines: 
    if line!= a[0]: 
    f.write(line) 
f.close() 

當我使用上面的代碼時,我的html文件中的所有其他行都被刪除。當你寫同一個文件,內容將覆蓋

 <h2>Thank you</h2> 
<h2>Please come again</h2> #Get rid of this line 
+4

不要用正則表達式處理HTML/XML ... –

+0

@WillemVanOnsem,[no fear](https://gist.github.com/mgsisk/1094230)! =) – grundic

+0

@grundic:我的觀點正是...... –

回答

0

文本試圖擺脫的。所以,你需要打開新的文件,並寫入該文件爲:

f = open("NEWFILE.html","w") 
for line in lines: 
    if line!= a[0]: 
    f.write(line) 
f.close() 
1

試試這個:用於XML/HTML

with open("myfile.html", "w+") as f: 
    content = f.read() 
    f.write(re.sub(r'<\s*h2[^>]*>(.*?)<\s*/\s*h2>', '', content)) 

但作爲@Willem範Onsem建議,不要使用正則表達式,使用BeautifulSoup的XML解析器lxml更加健壯。