python2到python3的转换以及f.write在python3 中的用法

.利用Python内置(Python脚本)工具,帮你自动转换

Python 2.x版本,比如我安装的Python 2.7.2,其在windows下载安装好之后,就自带了相关的一些有用的工具。

其中一个叫做2to3.py,就是用来帮你实现,将Python 2.x的代码,转换为Python 3.x的代码的。

其位置位于:Python安装的根目录\Python27\Tools\Scripts\2to3.py

 

【如何利用2to3.py,实现将Python 2.x的代码,转换为Python 3.x的代码】 
比如我手上有个Python 2.x的python脚本:

现在,想要将其转换为Python 3.x的代码。

可以通过打开windows的cmd,定位至该要转换的脚本下,然后运行

D:\Python27\Tools\Scripts\2to3.py -w jsontest.py


1.TypeError: must be str, not bytes错误:

解答: 写文件处 open(filename, 'w').write 应该写为 open(filename, 'wb').write

2.当文本文件里面有中文时,需要进行编码转换,(在网上查了很多都不行)

with open("C://ch.js", encoding="utf-8") as data1:
for oneLine in data1:
print(oneLine)

编码转换:content = str(open(filepath).read(),'gbk').encode('utf8')

当输出多一个b时加个decode(‘utf-8’)即可


http://www.crifan.com/how_to_convert_python2_into_python3/





posted @ 2016-11-09 14:55  fool鱼  阅读(599)  评论(0编辑  收藏  举报