python 用os.walk()遍历目录时,里面的中文文件名显示为乱码

toni0409 2011-06-17 02:30:06
#-*- coding:utf-8 -*-
import os,sys,string
export=" "
for root,dirs,files in os.walk(r'E:\testpython'):
export+="%s;%s;%s\n" %(root,dirs,files)

print export

该目录中有个文件名为“新建文本文档 (2).sql “的文件,但该程序返回结果中,该文件名显示为乱码:\xd0\xc2\xbd\xa8\xce\xc4\xb1\xbe\xce\xc4\xb5\xb5 (2).sql,请问大家该怎么解决呢,我看了好多关于python中文编码问题的文章,但是还是无法解决。
...全文
2673 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
HelloVisaya 2011-07-01
  • 打赏
  • 举报
回复
把coding 改成gbk就可以了

#-*- coding:gbk -*-
import os,sys,string
export=" "
for root,dirs,files in os.walk(r'E:\testpython'):
export+="%s;%s;%s\n" %(root,dirs,files)

print export
batmanlf 2011-06-29
  • 打赏
  • 举报
回复
ls 正解
你要知道当前系统是什么编码然后解码就可以了。
b'\xd0\xc2\xbd\xa8\xce\xc4\xb1\xbe\xce\xc4\xb5\xb5'.decode('gbk')
'新建文本文档'
yytsdly 2011-06-22
  • 打赏
  • 举报
回复
python里console窗口和写到文件里,显示效果是不一样的
在ulipad里运行显示出来的结果也可能不一样

python的编码很愁人....
livesguan 2011-06-22
  • 打赏
  • 举报
回复
可以显示中文的,首先你那个不是乱码,是WINDOWS下的GBK编码,可以转变为unicode就可以了.
tangxianghenggood 2011-06-22
  • 打赏
  • 举报
回复
核心编程有讲 可以借鉴一下啊
「已注销」 2011-06-20
  • 打赏
  • 举报
回复
#-*- coding:utf-8 -*-
import os,sys,string
output = open('output.txt', 'w')
for root,dirs,files in os.walk('.'):
for f in files:
print f
output.write(f + '\n')


哪里有见什么乱码。
iambic 2011-06-20
  • 打赏
  • 举报
回复
打印[1, 2, 3, 4]到文本里有什么意义吗?打印
1
2
3
4
不是更好吗?
toni0409 2011-06-20
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 angel_su 的回复:]

你可能在某个ide下执行的关系,标准windows shell下那些字是正常的...

Microsoft Windows XP [版本 5.1.2600]
(C) 版权所有 1985-2001 Microsoft Corp.

C:\Documents and Settings\Administrator\桌面>python
Python 2.7.1 (r271:86832, No……
[/Quote]
那我将输出的结果保存到一本文本文档中,刚才那段还是乱码啊,无法显示成中文,那这个才怎么解决呢
iambic 2011-06-18
  • 打赏
  • 举报
回复
你看到的是字符串的原始表示吧?应该就是内部使用,不影响你。不用害怕。
>>> '新建文本文档'
'\xd0\xc2\xbd\xa8\xce\xc4\xb1\xbe\xce\xc4\xb5\xb5'
angel_su 2011-06-17
  • 打赏
  • 举报
回复
你可能在某个ide下执行的关系,标准windows shell下那些字是正常的...

Microsoft Windows XP [版本 5.1.2600]
(C) 版权所有 1985-2001 Microsoft Corp.

C:\Documents and Settings\Administrator\桌面>python
Python 2.7.1 (r271:86832, Nov 27 2010, 18:30:46) [MSC v.1500 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print '\xd0\xc2\xbd\xa8\xce\xc4\xb1\xbe\xce\xc4\xb5\xb5'
新建文本文档
dontbecoder 2011-06-17
  • 打赏
  • 举报
回复
python不懂,帮顶

37,720

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • IT.BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧