python "AttributeError: 'str' object has no attribute 'decode'"错误

littleant1111 2013-05-10 02:53:15
代码如下:
=================================代码==========================
import re
f1=open('J:/wenjian/1/1.txt','r').read()#把整个文件读进来作为整个字符串
f1.decode()#把byte类型转换成string类型
f1=re.sub('abcdef','123456',f1)#替换所有符合的情况
print (f1)#此时已经替换成功
f_w=open('J:/wenjian/1/replace_1.txt','wb')#新建一个文件,把替换后的内容写进去
f1=f1.encode('utf-8')#从string转换成bytes类型
f_w.write(f1)#必须要是bytes类型才能写进去
f_w.close()
======================代码======================================
报错如下:
Traceback (most recent call last):
File "J:\wenjian\python\test.py", line 8, in <module>
f1.decode()#把byte类型转换成string类型
AttributeError: 'str' object has no attribute 'decode'
>>>

系统是win7*64 python 3.3.1版本。
望大侠帮助。真诚感谢。
...全文
78405 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
littleant1111 2013-05-11
  • 打赏
  • 举报
回复 1
引用 3 楼 panghuhu250 的回复:
python 3中只有unicode str,所以把decode方法去掉了。你的代码中,f1已经是unicode str了,不用decode。 如果文件内容不是unicode编码的,要先以二进制方式打开,读入比特流,再解码。

/tmp/ python3
Python 3.2.3 (default, Feb 20 2013, 14:44:27) 
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> f1 = open("unicode.txt", 'r').read()
>>> print(f1)
寒冷

>>> f2 = open("unicode.txt", 'rb').read() #二进制方式打开
>>> print(f2)
b'\xe5\xaf\x92\xe5\x86\xb7\n'
>>> f2.decode()
'寒冷\n'
>>> f1.decode()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'decode'
>>> 
不错。就是这样的
panghuhu250 2013-05-10
  • 打赏
  • 举报
回复
没仔细看过python 3,看来需要更新一下我的python知识了。
引用 4 楼 angel_su 的回复:
逻辑上,你用2进制读写,那就别再转换编码。考虑编码问题,py3k里open有参数指定文件编码,你就不需要decode来encode去...
angel_su 2013-05-10
  • 打赏
  • 举报
回复
逻辑上,你用2进制读写,那就别再转换编码。考虑编码问题,py3k里open有参数指定文件编码,你就不需要decode来encode去...
panghuhu250 2013-05-10
  • 打赏
  • 举报
回复
python 3中只有unicode str,所以把decode方法去掉了。你的代码中,f1已经是unicode str了,不用decode。 如果文件内容不是unicode编码的,要先以二进制方式打开,读入比特流,再解码。

/tmp/ python3
Python 3.2.3 (default, Feb 20 2013, 14:44:27) 
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> f1 = open("unicode.txt", 'r').read()
>>> print(f1)
寒冷

>>> f2 = open("unicode.txt", 'rb').read() #二进制方式打开
>>> print(f2)
b'\xe5\xaf\x92\xe5\x86\xb7\n'
>>> f2.decode()
'寒冷\n'
>>> f1.decode()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'decode'
>>> 
INeddy 2013-05-10
  • 打赏
  • 举报
回复
试了下3.1的环境,字符串貌似没有 decode 函数了,而且read 返回的不是字符串么?要转换编码?
wokao112358 2013-05-10
  • 打赏
  • 举报
回复
是不是还要import string?

37,719

社区成员

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

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