日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python读取ini文件编码格式_Python读取txt(.ini)文件BOM问题

發布時間:2024/10/8 python 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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问题的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。