1. 程式人生 > >python3 讀寫檔案換行符

python3 讀寫檔案換行符

最近在處理文字檔案時,遇到編碼格式和換行符的問題。

基本上都是GBK 和 UTF-8 編碼的文字檔案,但是python3 中預設的都是按照 utf-8 來開啟。用不正確的編碼引數開啟,在讀取內容時,會丟擲異常。

open(dirpath + "\\" + file, mode = "r+", encoding = "gbk", newline = "")

捕獲丟擲的異常,關閉檔案。使用另外一種編碼格式開啟檔案再重新讀取。

讀取檔案時,

newline引數用來指定讀取時,對換行符的處理。預設為 None,表示通用的換行符(“\n”),即檔案的換行符是啥,讀出來都是 “\n”.

newline = ""  表示讀取的換行符保持不變,原來是啥,讀出來還是啥。

newline = “\n”  表示遇到 "\n" 才一行結束,“\r” 像其他普通字元一樣對待。

newline = “\r”  表示遇到 "\r" 才一行結束,“\n” 像其他普通字元一樣對待。

在檔案寫入時,

newline = None時,寫入的“\n” 自動都變為系統預設的換行符。所以 “\r\n” 在windows下會變成“\r\r\n”寫入。

newline = ""  表示不做任何轉換寫入。

newline = “\n”  表示不做任何轉換寫入。

newline = “\r”  表示將 “\n” 和 "\r" 都當做 "\r" 進行寫入,所以“\r\n” 會變成 “\r\r”進行寫入。

案例:將原始碼下的所有makefile 檔案中的 -c 引數前,加上 -g 選項。

import os
import re

os.chdir(r"E:\code")
s = os.walk(".")
pattern = re.compile(r"\s-c\s")
for dirpath, dirnames, filenames in s:
	for file in filenames:
		if file.endswith(".mak") or "makefile" in file:    #部分以 .mak 結尾,部分以makefile命名
			print(file)
			with open(dirpath + "\\" + file, mode = "r+", encoding = "gbk", newline = "") as f:  #newline為空串表示換行符不轉換
				try:    #編碼問題造成的異常
					lines = f.readlines()  #一次讀取所有的行到記憶體
					f.seek(0)               #回到檔案起始處
					for line in lines:
						#newline = line.replace(" -c "," -g -c ")
						newline= re.sub(pattern, " -g -c ", line)
						f.write(newline)
				except ValueError:
					f.close()
					with open(dirpath + "\\" + file, mode = "r+", encoding = "utf-8", newline = "") as fnew:
						try:    
							lines = fnew.readlines()  
							fnew.seek(0)             
							for line in lines:
								#newline = line.replace(" -c "," -g -c ")
								newline= re.sub(pattern, " -g -c ", line)
								fnew.write(newline)
						except ValueError:
							print("***************  " + dirpath + "\\" + file)    #列印utf-8 和 gbk 之外編碼的檔名