python读取ini文件编码格式_Python读取txt(.ini)文件BOM问题
2018-06-13? ?11:20:40
在windows上使用open打開utf-8編碼的txt文件時開頭會有一個多余的字符,它叫BOM,是用來聲明編碼等信息的,但python會把它當作文本解析
解決辦法:open的encoding參數
1.創建config.ini配置文件
[DATABASE]
host= 50.23.190.57username=xxxxxx
password= ******port= 3306database=databasename
[HTTP]#接口的url
baseurl = https://xxxxxxxxx
port= 8080timeout= 1.0[EMAIL]
mail_host= smtp.163.com
mail_user= xxx@163.com
mail_pass= *********mail_port= 25sender= xxx@163.com
receiver= xxxx@qq.com/xxxx@qq.com
subject=python
content= "All interface test has been complited\nplease read the report file about the detile of result in the attachment."testuser=Someone
on_off= 1
2.讀取config.ini配置文件
importosimportcodecsimportconfigparser#獲取當前文件__file__的所在目錄
proDir = os.path.split(os.path.realpath(__file__))[0]#獲取文件 cfg.ini 的地址
configPath = os.path.join(proDir, "config.ini")print(configPath)classReadConfig:def __init__(self):
self.cf=configparser.ConfigParser()
self.cf.read(configPath)defget_email(self, name):
value= self.cf.get("EMAIL", name)returnvaluedefget_http(self,name):
value= self.cf.get("HTTP", name)print(value)returnvaluedefget_db(self, name):
value= self.cf.get("DATABASE", name)return value
運行結果報錯:
在首行添加? ?#coding=gbk,其余代碼均不變
#coding=gbk 固定編碼格式為 gbk
importosimportcodecsimport configparser
運行結果報錯:
用encoding參數讀取文件
#coding=gbk
importosimportcodecsimportconfigparser#獲取當前文件__file__的所在目錄
proDir = os.path.split(os.path.realpath(__file__))[0]#獲取文件 cfg.ini 的地址
configPath = os.path.join(proDir, "config.ini")print(configPath)classReadConfig:def __init__(self):
self.cf=configparser.ConfigParser()
self.cf.read(configPath,encoding='utf-8') #encoding='utf_8_sig'
運行結果成功:
3.utf-8 與 utf-8-sig兩種編碼格式的區別
UTF-8以字節為編碼單元,它的字節順序在所有系統中都是一様的,沒有字節序的問題,也因此它實際上并不需要BOM(“ByteOrder Mark”), 但是UTF-8 with BOM即utf-8-sig需要提供BOM("ByteOrder Mark")
這里我不是很理解,反正在這里無論用那種編碼格式都可以
self.cf.read(configPath,encoding='utf-8') #encoding='utf_8_sig'
#執行zip壓縮命令,將apitest目錄下所有文件打包壓縮
source =[back_dir,back_file]
target_file=target_dir+time.strftime("%Y%m%d%H%M%S")+'.zip'zip_commond="zip -qr \"%s\" \"%s\""%(target_file,''.join(source))print(zip_commond)if os.system(zip_commond)==0:print('Successful backup to',target_file)else:print('Backup Failed')
總結
以上是生活随笔為你收集整理的python读取ini文件编码格式_Python读取txt(.ini)文件BOM问题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python怎么做q检验_统计学_Coc
- 下一篇: python登录接口代码_(转载)Pyt