[問題] Python寫入文字檔的問題

看板Python作者 (mhsu2k9)時間14年前 (2012/01/19 16:17), 編輯推噓0(004)
留言4則, 2人參與, 最新討論串1/1
我最近為了跨平台使用,使用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

01/19 18:28, , 1F
有可能該CSS文檔的換行為'\r\n',而被編輯器視為兩次換行
01/19 18:28, 1F

01/19 18:29, , 2F
可以用 print repr(cssText) 檢查看看換行的部分
01/19 18:29, 2F

04/03 04:11, , 3F
用binary mode開啟新檔就解決了
04/03 04:11, 3F

04/03 04:12, , 4F
FILE=open(fileName,"w") 改成 FILE=open(fileName,"wb")
04/03 04:12, 4F
文章代碼(AID): #1F5z67Xo (Python)
文章代碼(AID): #1F5z67Xo (Python)