python读取Unicode和ANSI编码的文件

最近需要操作inf格式文档,用原本的文本读取方式不成功,于是搜索了一下找到原因。需要读取的目录下的文件有两种编码方式,一种是ANSI,另外一种是Unicode,但是Unicode的存储方式有UTF-8,UTF-16等,UTF即为Unicode Translation Format,就是把Unicode转做某种格式的意思。读取Unicode编码方式的文本时需要标明其存储方式,否则会出错。


如下代码可以读取指定目录下面以"test"为前缀以".txt"为后缀的文本文件(文件可以存在子目录下),搜索到其中是否含有"done"字串,若有则输出其文件夹路径,其完整路径还有含有该字串的行。搜索完毕后将搜索到的文件完整路径存在一个list中并再次输出。

import os.path
import codecs

rootdir = "C:\\test\\code_python\\testfile"

def lookupstring(lookup):
    filelist = []
    judge = False
    for parent, dirnames, filenames in os.walk(rootdir):
        for filename in filenames:
            if filename.startswith("test") and filename.endswith(".txt"):
                try:
                    f = codecs.open(os.path.join(parent, filename), 'r', 'utf-16')
                    ls = [ line.strip() for line in f]
                    for line in ls:
                        if not line.find(lookup) == -1:
                            print "parent is:" + parent
                            print "filename with full path :" + os.path.join(parent, filename)
                            print line
                            judge = True
                    if judge == True:
                        filelist.append(os.path.join(parent, filename))
                    judge = False
                    f.close()
                except:
                    f.close()
                    f = open(os.path.join(parent, filename), 'r')
                    ls = f.readlines()
                    for line in ls:
                        if not line.find(lookup) == -1:
                            print "parent is:" + parent
                            print "filename with full path :" + os.path.join(parent, filename)
                            print line
                            judge = True
                    if judge == True:
                        filelist.append(os.path.join(parent, filename))
                    judge = False
                    f.close()
    return filelist
                    
def main():
    test = lookupstring("done")
    for element in test:
        print element

if __name__ == '__main__':
    main()

猜你喜欢

转载自blog.csdn.net/skeleton703/article/details/8433375
今日推荐