引入configparser,直接read整个INI文件,再调用get即可。但需要注意的是,如果INI文件本身不太规范,就会报各种错,而这又常常不可避免的。本文自定义函数通过try...except..来自动纠正再重读。

此外,注册表导出文件大概齐就是INI文件格式,但取初一行的声明也会被认定为没有SECTION头而报错。本文也进行了自动纠正。

极大概率是早有人造过更好的轮子,我写在这里权当作自己学习Python的笔记。功能、特色如下:

  1. getINIValue函数三个参数,iniFile, section, option应该不用特别说明;
  2. 若iniFile本身不存在或未知异常,返回None,同时输出报错信息;
  3. INI文件编码自动尝试,目前顺序为gb2312 utf-8 utf-16 gbk gb18030;
  4. INI文件内容不规范(section或option重复异常即configparser.DuplicateSectionError, configparser.DuplicateOptionError)自动纠正(注释后面的,以前面的为准);
  5. 注册表导出Reg文件不符合INI规范(缺少SECTION头异常即configparser.MissingSectionHeaderError)自动纠正(注释最初行);
  6. 找不到Option(考虑到一种情况:上位指定.reg的Option时没加",自动追加);
  7. 自动纠正INI文件时产生的备份文件自动删除。

Python源码如下,欢迎讨论指正....

 import configparser
import os bakpostfix = '.ibk' ## [修正不规则INI文件]
def __iniFileFix(errorline, iniFile, encoding):
# 备份INI文件名
newIniFile = iniFile + bakpostfix try:
fr = open(iniFile, 'r', encoding=encoding)
fw = open(newIniFile, 'w', encoding=encoding)
# 逐行读取
line = fr.readline()
lineno = 1
while line != '':
# 若到了问题行,则注释它
if lineno == int(errorline):
line = '; ' + line
# 逐行写入(修正后)
fw.writelines(line)
line = fr.readline()
lineno += 1
fr.close()
fw.close()
except Exception as e:
# 异常时返回报错信息
error = 'Error:[{0}]'.format(e)
print(error)
return error
# 正常时返回新文件名
return newIniFile ## [读取INI文件]
def getINIValue(iniFile, section, option):
config = configparser.ConfigParser()
value = '' # 备份文件
bBakFile = False # 异常:文件不存在
if (os.path.isfile(iniFile) == False):
print('Error: file "{0}" not exists...'.format(iniFile))
return None bException = True
# 尝试编码的次数
counter = 1
# 多次循环尝试修正INI为正确的格式,直到正常或遇到无法处理的异常
while bException:
try:
encoding = ''
# 依次进行如下编码打开尝试(后续根据需要添加)
if counter == 1: encoding = 'gb2312'
if counter == 2: encoding = 'utf-8'
if counter == 3: encoding = 'utf-16'
if counter == 4: encoding = 'gbk'
if counter == 5: encoding = 'gb18030'
if counter == 6:
# 暂无法处理的编码
print('Error: encoding unknown...')
return None
config.read(iniFile, encoding=encoding)
bException = False
except UnicodeDecodeError as e:
# 编码异常
print('Error:[{0}]'.format(e))
counter += 1
except (configparser.DuplicateSectionError, configparser.DuplicateOptionError) as e:
# SECTION重复异常
# Option重复异常
print('Error:[{0}]'.format(e))
excep = '{0}'.format(e)
errorline = excep[excep.find(' [line ') + len(' [line '):excep.find(']', excep.find(' [line '))]
iniFile = __iniFileFix(errorline, iniFile, encoding)
if iniFile.find('Error:[') == 0:
return None
bBakFile = True
except configparser.MissingSectionHeaderError as e:
# 缺少SECTION头异常
print('Error:[{0}]'.format(e))
excep = '{0}'.format(e)
errorline = excep[excep.find(', line: ') + len(', line: '):excep.find('\n', excep.find(', line: '))]
iniFile = __iniFileFix(errorline, iniFile, encoding)
if iniFile.find('Error:[') == 0:
return None
bBakFile = True
except Exception as e:
# 未知新异常(后续根据需要追加)
print('Error:[{0}]'.format(e))
return None # 删除INI备份文件
if bBakFile == True:
# 可能存在多个INI备份,循环删除
bMoreBakFile = True
while (bMoreBakFile):
os.remove(iniFile)
iniFile = iniFile[0:iniFile.rfind(bakpostfix)]
if iniFile.rfind(bakpostfix) == -1 :
bMoreBakFile = False # 多次循环尝试修正INI为正确的格式,直到正常或遇到无法处理的异常
bException = True
while bException:
try:
value = config.get(section, option)
bException = False
except configparser.NoSectionError as e:
# 找不到SECTION
print('Error:[{0}]'.format(e))
return None
except configparser.NoOptionError as e:
# 找不到Option(考虑到一种情况:上位指定.reg的Option时没加",自动追加)
print('Error:[{0}]'.format(e))
if option[0] != '"' and option[len(option)-1] != '"':
option = '"' + option + '"'
else :
return None
except Exception as e:
# 未知新异常(后续根据需要追加)
print('Error:[{0}]'.format(e))
return None return value

python学习笔记~INI、REG文件读取函数(自动修复)的更多相关文章

  1. Head First Python 学习笔记-Chapter3:文件读取和异常处理

    第三章中主要介绍了简单的文件读取和简单的异常处理操作. 首先建立文件文件夹:HeadFirstPython\chapter3,在Head First Pythong官方站点下载须要使用的文件:sket ...

  2. Python学习笔记之从文件中读取数据

    10-1 Python 学习笔记:在文本编辑器中新建一个文件,写几句话来总结一下你至此学到的Python 知识,其中每一行都以“In Python you can”打头.将这个文件命名为learnin ...

  3. Python学习笔记之—— File(文件) 对象常用函数

    file 对象使用 open 函数来创建,下表列出了 file 对象常用的函数: 1.file.close() close() 方法用于关闭一个已打开的文件.关闭后的文件不能再进行读写操作, 否则会触 ...

  4. 转载-python学习笔记之输入输出功能读取和写入数据

    读取.写入和 Python 在 “探索 Python” 系列以前的文章中,学习了基本的 Python 数据类型和一些容器数据类型,例如tuple.string 和 list.其他文章讨论了 Pytho ...

  5. Python学习笔记六:文件处理

    一:打开文件 open(name,mode,[bufferSize]) name:文件路径 mode:文件打开方式 二:文件读取 read()方法:可以一次读取文件的全部内容,Python把内容读到内 ...

  6. 【学习笔记】tensorflow文件读取

    目录 文件读取 文件队列构造 文件阅读器 文件内容解码器 开启线程操作 管道读端批处理 CSV文件读取案例 先看下文件读取以及读取数据处理成张量结果的过程: 一般数据文件格式有文本.excel和图片数 ...

  7. Python学习笔记八:文件操作(续),文件编码与解码,函数,递归,函数式编程介绍,高阶函数

    文件操作(续) 获得文件句柄位置,f.tell(),从0开始,按字符数计数 f.read(5),读取5个字符 返回文件句柄到某位置,f.seek(0) 文件在编辑过程中改变编码,f.detech() ...

  8. Python学习笔记_从CSV读取数据写入Excel文件中

    本示例特点: 1.读取CSV,写入Excel 2.读取CSV里具体行.具体列,具体行列的值 一.系统环境 1. OS:Win10 64位英文版 2. Python 3.7 3. 使用第三方库:csv. ...

  9. python学习笔记3.1_数据读取常用函数参数

    一.read_table/read_csv常用函数参数 1.path:表明文件系统位置的字符串.url或文件型对象 2.sep或delimiter:用于分隔每行字段的字符序列或正则表达式 3.head ...

随机推荐

  1. python调用chrome打开指定网址

    #!/usr/bin/python # -*- coding:utf-8 -*- import os f = open("chrome_cmd_path.txt") chrome ...

  2. July 02nd 2017 Week 27th Sunday

    No safe wading in an unknown water. 未知水深浅,涉水有危险. Is this the theory that has been the guideline for ...

  3. hiredis

    hiredis是redis开源库对外发布的客户端API包. 当redis-server配置启动后,可以通过hiredis操作redis资源. 主要分为: strings.hash.lists.sets ...

  4. How to update BOL entity property value via ABAP code

    Suppose I have one product with ID I042416 which could be found in CRM WebClient UI: I would like to ...

  5. 智能指针之auto_ptr和scoped_ptr

    部分参考地址https://blog.csdn.net/yanglingwell/article/details/56011576 auto_ptr是c++标准库里的智能指针,但是具有以下几个明显的缺 ...

  6. ThreadLocal介绍

    作者:知乎用户链接:https://www.zhihu.com/question/23089780/answer/62097840来源:知乎著作权归作者所有.商业转载请联系作者获得授权,非商业转载请注 ...

  7. 字符串匹配KMP算法(转自阮一峰)

    转自 http://www.ruanyifeng.com/blog/2013/05/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm.html 字符串匹配是计算 ...

  8. ASP.NET SingalR + MongoDB 实现简单聊天室(一):搭建基本框架

    ASP.NET SingalR不多介绍.让我介绍不如看官网,我这里就是直接上源代码,当然代码还是写的比较简单的,考虑的也少,希望各位技友多多提意见. 先简单介绍聊天室功能: 用户加入聊天室,自动给用户 ...

  9. 安装JDK8

    安装JDK8 1.去http://www.Oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html中下载JDK的 ...

  10. 用python实现ping

    #!/usr/bin/env python #coding=utf-8 import os import argparse import socket import struct import sel ...