Python遍历路径下文件并转换成UTF-8编码
2014-01-17 10:02
477 查看
/article/4935222.html
开始学Python,这篇文章来自于应用需求。
os.walk很方便,下面写了两个版本的函数进行遍历,分别是不使用walk和使用walk的。
另外附上使用第一种方法转换文件编码的源码,有的文件转换后用gedit打开是乱码,但用vi查看是正确的。
1.14更新:发现linux自带的iconv -f gb18030 -t utf8 a.txt >> b.txt更好用,而且有的用decode("gb18030")会出现乱码("gbk"一样乱码)的情况不再存在。在python脚本不难调用,就不详细写了。
开始学Python,这篇文章来自于应用需求。
os.walk很方便,下面写了两个版本的函数进行遍历,分别是不使用walk和使用walk的。
import sys import string import os def detect_nowalk(dir_path): files = os.listdir(dir_path) for filename in files: print "file:%s\n" % filename next = os.path.join(dir_path, filename) if os.path.isdir(next): print "file folds:%s\n" % filename detect_nowalk(next) if __name__ == "__main__": detect_nowalk(".")
import sys import os def detect_walk(dir_path): for root, dirs, files in os.walk(dir_path): for filename in files: print "file:%s\n" % filename for dirname in dirs: print "dir:%s\n" % dirname if __name__ == "__main__": detect_walk(".")
另外附上使用第一种方法转换文件编码的源码,有的文件转换后用gedit打开是乱码,但用vi查看是正确的。
import sys import string import codecs import os import shutil def gbkToUtf8(path): files = os.listdir(path) for filename in files: if os.path.isdir(filename): print "file folds:%s\n" % filename gbkToUtf8(filename) continue try: tokens = string.splitfields(filename, '.') if len(tokens) != 2 or tokens[1] != 'txt': #print tokens[1] continue else: print 'Encode Converting (GBK to UTF-8) : ', filename utfFile=open(filename) tstr = utfFile.read() #tstr = utfFile.read().decode("gbk") is wrong tstr = tstr.encode("UTF-8") utfFile.close() utfFile = open(filename, 'w') utfFile.write(tstr) utfFile.close() except: print "error %s" %filename if __name__ == "__main__": gbkToUtf8(".")
1.14更新:发现linux自带的iconv -f gb18030 -t utf8 a.txt >> b.txt更好用,而且有的用decode("gb18030")会出现乱码("gbk"一样乱码)的情况不再存在。在python脚本不难调用,就不详细写了。
相关文章推荐
- Python遍历路径下文件并转换成UTF-8编码
- Python遍历路径下文件并转换成UTF-8编码
- Python遍历路径下文件并转换成UTF-8编码
- [Python爬虫] 中文编码问题:raw_input输入、文件读取、变量比较等str、unicode、utf-8转换问题
- Python读取Unicode编码格式的文件(转换为UTF-8)
- [Python] 中文编码问题:raw_input输入、文件读取、变量比较等str、unicode、utf-8转换问题
- 文件转换为utf-8编码(python小脚本)
- 利用nodepad++中的python script插件批量转换文件编码为utf-8
- 【整理】关于Python脚本开头两行的:#!/usr/bin/python和# -*- coding: utf-8 -*-的作用 – 指定文件编码类型
- linux批量转换整个目录下的文件编码为UTF-8
- .java文件的ANSI编码转换为UTF-8编码
- 如何在 Linux 中将文件编码转换为 UTF-8
- python 对文件编码格式转换小工具
- Ubuntu转换文件编码格式(gbk to utf-8 )
- Python文件的编码注释 utf-8
- iconv将文件编码从gb2312 转换为utf-8
- python解析plist文件gb2312编码格式到utf-8编码格式
- Python编码UNICODE GBK UTF-8字符集转换的正确姿势
- Python os.walk遍历出某路径下所有文件
- Python遍历路径下所有文件