天天看點

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.57
username = xxxxxx
password = ******
port = 3306
database = databasename

[HTTP]
# 接口的url
baseurl = https://xxxxxxxxx
port = 8080
timeout = 1.0

[EMAIL]
mail_host = smtp.163.com
mail_user = [email protected]
mail_pass = *********
mail_port = 25
sender = [email protected]
receiver = [email protected]/[email protected]
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配置檔案

import os
import codecs
import configparser

#擷取目前檔案__file__的所在目錄
proDir = os.path.split(os.path.realpath(__file__))[0]
#擷取檔案 cfg.ini 的位址
configPath = os.path.join(proDir, "config.ini")
print(configPath)

class ReadConfig:
    def __init__(self):
        self.cf = configparser.ConfigParser()
        self.cf.read(configPath) 

    def get_email(self, name):
        value = self.cf.get("EMAIL", name)
        return value

    def get_http(self,name):
        value = self.cf.get("HTTP", name)
        print(value)
        return value

    def get_db(self, name):
        value = self.cf.get("DATABASE", name)
        return value          

運作結果報錯:

Python讀取txt(.ini)檔案BOM問題

在首行添加   #coding=gbk,其餘代碼均不變

#coding=gbk  固定編碼格式為 gbk
import os
import codecs
import configparser      
Python讀取txt(.ini)檔案BOM問題

用encoding參數讀取檔案

#coding=gbk
import os
import codecs
import configparser

#擷取目前檔案__file__的所在目錄
proDir = os.path.split(os.path.realpath(__file__))[0]
#擷取檔案 cfg.ini 的位址
configPath = os.path.join(proDir, "config.ini")
print(configPath)

class ReadConfig:
    def __init__(self):
        self.cf = configparser.ConfigParser()
        self.cf.read(configPath,encoding='utf-8') #encoding='utf_8_sig'      

運作結果成功:

Python讀取txt(.ini)檔案BOM問題

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')