- __author__ = 'soso_fy'
- #codeing:utf-8
- # 写python脚本经常要用到的一些函数
- # 免得每次都重写蛋疼
- # require python 3.2 or later
- import os
- import codecs
- # 读取文本文件函数,支持bom-utf-8,utf-8,utf-16,gbk,gb2312
- # 返回文件内容
- def ReadTextFile(filepath):
- try:
- file = open(filepath, 'rb')
- except IOError as err:
- print('读取文件出错 in ReadFile', err)
- bytes = file.read()
- file.close()
- if bytes[:3] == codecs.BOM_UTF8:
- content = bytes[3:].decode('utf-8')
- else:
- try:
- content = bytes.decode('gb2312')
- except UnicodeDecodeError as err:
- try:
- content = bytes.decode('utf-16')
- except UnicodeDecodeError as err:
- try:
- content = bytes.decode('utf-8')
- except UnicodeDecodeError as err:
- try:
- content = bytes.decode('gbk')
- except UnicodeDecodeError as err:
- content = ''
- print('不支持此种类型的文本文件编码', err)
- return content
- # 获取指定路径下所有指定后缀的文件
- # dir 指定路径
- # ext 指定后缀,链表&不需要带点或者不指定。例子:['xml', 'java']
- def GetFileFromThisRootDir(dir,ext = None):
- allfiles = []
- needExtFilter = (ext != None)
- if needExtFilter:
- ext = list(map(lambda x:x.lower(), ext))
- for root,dirs,files in os.walk(dir):
- for filespath in files:
- filepath = os.path.join(root, filespath).lower()
- extension = os.path.splitext(filepath)[1][1:]
- if needExtFilter and extension in ext:
- allfiles.append(filepath)
- elif not needExtFilter:
- allfiles.append(filepath)
- return allfiles
- #该片段来自于http://www.codesnippet.cn/detail/220720134740.html
来源: http://www.codesnippet.cn/detail/220720134740.html