免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1481 | 回复: 3
打印 上一主题 下一主题

请教 python 的代码错误在哪里? [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2012-07-27 16:21 |只看该作者 |倒序浏览
请教 python 的代码错误在哪里?
# 以下是统计程序代码行数的代码
# 我的目的是统计 d:\ywgl2 下,所有的 *.ini,*.bas,*.frm 的文件总行数,
# 但是有一个问题,
# Traceback (most recent call last):
#File "D:/ywgl2/a2.py", line 13, in <module>
#   data = f.read()
# UnicodeDecodeError: 'gbk' codec can't decode bytes in position 598-599: illegal multibyte sequence
# 不知以上提示是什么意思?

import os
lines_count = 0
for roots,dirs,files in os.walk('d:/ywgl/'):
    for file in files:
        if file[-4:]=='.ini' or file[-4:]=='.bas':
            f = open(os.path.join(roots, file))
            data = f.read()
            f.close()
            lines_count += data.count('\n')
   
print ("all lines count:%d" %lines_count)

论坛徽章:
0
2 [报告]
发表于 2012-07-27 16:49 |只看该作者
文件中就是包含汉字,
这种情况下,应该如何处理呢?

论坛徽章:
0
3 [报告]
发表于 2012-07-28 18:27 |只看该作者
我知道了,是编码的问题。
下面代码可以:
  1. import os
  2. import codecs
  3. lines_count = 0
  4. for roots,dirs,files in os.walk('d:/ywmis/'):
  5.     for file in files:
  6.         if file[-4:]=='.bas' or file[-4:]=='.frm' or file[-4:]=='.sql' or file[-4:]=='.cls':
  7.             f = codecs.open(os.path.join(roots, file),'r','gbk')
  8.             data = f.read()
  9.             f.close()
  10.             lines_count += data.count('\n')
  11.             if not data.endswith('\n'):
  12.                 lines_count += 1
  13.    
  14. print ("all lines count:%d" %lines_count)
复制代码
但还是不解,
我的系统是 winxp,所以格式是 ansi编码。
为何不能用 utf8统一处理呢?
都转成 gbk也不行呀,如果存在 utf8编码的如何办。
即有的文件是 gbk编码,有的文件是 utf8 编码

论坛徽章:
2
CU大牛徽章
日期:2013-04-17 11:46:28CU大牛徽章
日期:2013-04-17 11:46:39
4 [报告]
发表于 2012-07-28 19:07 |只看该作者
本帖最后由 cdtits 于 2012-07-28 19:08 编辑

用“binary”模式处理吧
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP