Python遍历路径下文件并转换成UTF-8编码
2023-09-14 08:58:25 时间
http://www.cnblogs.com/wuyuegb2312/archive/2013/01/11/2856772.html
开始学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脚本不难调用,就不详细写了。
相关文章
- 在pycharm中如何新建Python文件?_github下载的python源码项目怎么用
- python .txt文件读取及数据处理总结
- python qt是什么_初识Python与Qt「建议收藏」
- python解压bz2文件命令,在Python中解压缩.bz2文件
- Python学习:如何实现文件编码的检测
- python字典移除_python修改字典
- 【说站】python Pandas读取数据文件的优点
- 【说站】python文件路径的组成
- 【说站】python scrapy.Request发送请求的方式
- 【说站】如何检查文件是否有Python的符号链接?
- python打开h5文件可视化_python环境变量的配置
- Python 反转字符串_python输出字符串
- python判断文件后缀_Python 判断文件后缀是否被篡改
- python读取log文件_python分析log日志
- Python将数据写入txt文件_python将内容写入txt文件
- Python 操作XML文件一文通
- Python 接口测试之ddt数据驱动番外篇
- python-数据库编程-如何在Python中连接到数据库
- python-Python与PostgreSQL数据库-使用Python执行PostgreSQL查询(一)
- Redis分布式锁python-redis-lock使用方法
- python通过win32com库播放mp3文件详解编程语言
- python下载文件时显示下载进度的代码详解编程语言
- Python实现Oracle数据库连接(python连接oracle数据库)
- Linux系统下安装Python模块指南(linux安装python模块)
- python基础入门详解(文件输入/输出内建类型字典操作使用方法)