我有以下簡單的HTML
文件。Python搜索和替換不工作
<html data-noop=="http://www.w3.org/1999/xhtml">
<head>
<title>Hello World</title>
</head>
<body>
SUMMARY1
hello world
</body>
</html>
我想讀這爲python
腳本,並與文本「您好」(說)取代SUMMARY1。我這樣做的python
with open('test.html','r') as htmltemplatefile:
htmltemplate = htmltemplatefile.read().replace('\n','')
htmltemplate.replace('SUMMARY1','hi there')
print htmltemplate
上面的代碼文件中讀入變量htmltemplate
。 接下來我調用字符串對象的replace()
函數以將「hi there」替換爲SUMMARY1模式。但是輸出似乎沒有搜索並用「hi there」代替SUMMARY1。這是我得到的。
<html data-noop=="http://www.w3.org/1999/xhtml"><head><title>Hello World</title></head><body>SUMMARY1hello world</body></html>
有人能指出我在做什麼錯嗎?
因爲open()不返回一個字符串對象,所以它返回一個文件對象。此外,你只打開文件閱讀(''r'')。這也是一個重複:http://stackoverflow.com/questions/39086/search-and-replace-a-line-in-a-file-in-python – dursk 2015-02-24 19:13:05
我認爲我所做的錯誤是在行3.我將它更改爲
htmltemplate = htmltemplate.replace('SUMMARY1','hi there')
,它工作。 – broccoli 2015-02-24 19:35:52您還添加了'.read()'這不在你原來的文章中,並且有很大的改變。但不管怎樣,你仍然沒有真正編輯文件,''SUMMARY''仍然會出現在'test.html'中。 – dursk 2015-02-24 21:18:59