Python3 Read configuration file (Utf-8/utf-8-bom)

Source: Internet
Author: User

Background

Windows Notepad will add BOM headers to the UTF-8 file, annoying, and get a generic read of the configuration file code.


"Config.ini"

[Config] Srcroot=d:\inputdstroot=d:\output


"T.py"

#encoding =utf-8#author: walker#date: 2018-03-31#summary:  Read  UTF-8/UTF-8-BOM  Configuration file Import os, sysfrom configparser import configparsersrcroot = r ' DstRoot  = r "#读取配置文件def  readconfig (): Global srcroot, dstrootcfg = configparser () cfgfile =  ' Config.ini ' if not os.path.exists (cfgfile): Input (cfgfile +  '  not  found ') sys.exit ( -1) with open (cfgfile, mode= ' RB ')  as f:content = f.read () if  content.startswith (b ' \xef\xbb\xbf '):     #  remove  utf8 bom  Head content = content[3:]cfglst = cfg.read (cfgfile, encoding= ' Utf-8-sig ') If len ( CFGLST)  < 1:input (' read config.ini failed ... ') sys.exit ( -1) srcroot = cfg.get (' Config ',  ' srcroot '). Strip () if not os.path.exists (srcroot):p rint (' error: not exists  %s '  % srcroot) syS.exit ( -1) print (' srcroot: %s '  % srcroot) dstroot = cfg.get (' config ',  ' DstRoot '). Strip () if not os.path.exists (dstroot):p rint (' error: not exists %s '  %  Dstroot) sys.exit ( -1) print (' dstroot: %s '  % dstroot) print (' read config.ini successed! ') if __name__ ==  ' __main__ ': Readconfig ()


"CMD"

Λpython3 T.pysrcroot:d:\inputdstroot:d:\outputread Config.ini successed!


Walker * * *


Python3 Read configuration file (Utf-8/utf-8-bom)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.