作者mhsu2k9 (mhsu2k9)
看板Python
標題[問題] Python寫入文字檔的問題
時間Thu Jan 19 16:17:08 2012
我最近為了跨平台使用,使用Python2寫一支小程式
裡面有一部份是要抓 html裡面的 css tag,如果有找到css tag,就再去抓該css的地址
並讀取其文字內容,再寫回html檔案,只是這樣寫回去,我再用文字編輯器打開看,
寫回的css每一行之間都會再 "多空一行",雖然使用上無差別,但是還是有點惱人
請各位先進提點
謝謝
code 大致如下
#把網頁內容讀入htmlSource
urlItem = urllib2.urlopen("
http://xxx/xx.html)
htmlSource = urlItem.read()
urlItem.close()
#取得css位置的css文字檔,並取代原有的css tag
regex = re.compile("(<link href=[\'\"]?([^\'\"]*)[\'\"]?[^>]*>)")
match = regex.findall(htmlSource);
for m in match:
cssTag = m[0]
cssLocation = m[1]
cssText = urllib2.urlopen(cssLocation).read()
htmlSource = htmlSource.replace(cssTag, "<style>" + cssText +
"</style>")
#寫入檔案
fileName = outputLocation
FILE = open(fileName,"w")
FILE.write(codecs.BOM_UTF8)
FILE.write(htmlSource)
FILE.close()
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 60.248.90.133
→ apua:有可能該CSS文檔的換行為'\r\n',而被編輯器視為兩次換行 01/19 18:28
→ apua:可以用 print repr(cssText) 檢查看看換行的部分 01/19 18:29
→ mhsu2k9:用binary mode開啟新檔就解決了 04/03 04:11
→ mhsu2k9:FILE=open(fileName,"w") 改成 FILE=open(fileName,"wb") 04/03 04:12