Python2和Python3读取文本文件的区别及说明
作者:AllardZhao
这篇文章主要介绍了Python2和Python3读取文本文件的区别及说明,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
Python2和3读取文本文件的区别
如何读写文本文件?
实际案例
- 某文本文件编码格式已知(如UTF-8,GBK,BIG5)
- 在python 2.x和python 3.x中分别如何读取该文件?
解决方案
- python 2.x:写入文件前对unicode编码,读入文件后对二进制字符串解码。
- python 3.x:open函数指定't'的文本模式,encoding指定编码格式。
代码演示
# Python2中的文本文件读写
'''
文本也就是unicode字符串,在写入文件前要对unicode字符串指定某种格式的编码,
将它变成str这种形式,python2中str为连续的字节,只有这些字节才能存储到物理设备上去。
读取文件的时候就是反过来,读入的也是一些字节,将其进行解码还原成unicode也就是文本。
'''
# 写入文本
f1 = open('py2.txt', 'w')
s = u'你好'
f1.write(s.encode('gbk'))
f1.close()
# 读取文本
f1 = open('py2.txt', 'r')
t = f1.read()
print(t.decode('gbk'))
--------------------------------------------------------------
# Python3中的文本文件读写
'''
python3中的字符串定义上更加明确了,原来的str变成了bytes(一系列字节);
原来的unicode变成了真正意义上的字符串。
python2中定义bytes字符串也就是字节字符串的时候,只需要这样写'sdfsger',
但是在python3中要加一个小b,如:b'sdfsger'。
unicode在python2中前面要加一个小u,这才表示unicode字符产,如:u'你好';
但是在python3中字符串的含义它直接就是unicode字符串,所以不用写小u,如:'你好'。
这就是Python2和Python3之间字符串的差别
'''
# 写入文本,t为文本模式不写也是默认为t打开,格式为utf8
f2 = open('py3.txt', 'wt', encoding='utf8')
f2.write('你好,我爱编程。')
f2.close()
# 读取文本
f2 = open('py3.txt', 'rt', encoding='utf8')
s = f2.read()
print(s)
'''
Python3中指定encoding会自动帮我们进行编码和解码,
而python2中就需要你手动进行编码和解码。
'''python读取文件(三种方式)
首先,获取文件对象
file = "F://content.txt" f = open(file, 'r', encoding='utf-8') list = f.readlines()
方法一:直接打印
# 方法1:直接打印 print(list)
方法二:while循环
print('----------方法2:while循环1----------------')
# 方法2:while循环
f = open(file, 'r', encoding='utf-8')
while True:
line = f.readline()
if len(line)==0:
break
print(line.strip('\n'))
print('----------方法2:while循环2----------------')
while length>0:
print(list[i][:-1])
i+=1
length-=1方法三:for循环
# 方法3:for循环
for i in list:
print(i.strip())所有代码:
file = "F://content.txt"
f = open(file, 'r', encoding='utf-8')
list = f.readlines()
print('-------------方法1:直接打印----------------')
# 方法1:直接打印
print(list)
length = len(list)
i=0
print('----------方法2:while循环1----------------')
# 方法2:while循环
file = "F://content.txt"
while True:
line = f.readline()
if len(line)==0:
break
print(line.strip('\n'))
print('----------方法2:while循环2----------------')
while length>0:
print(list[i][:-1])
i+=1
length-=1
print('---------方法3:for循环-------------------')
# 方法3:for循环
for i in list:
print(i.strip())测试文本:
bbb aa dd
cc aa cc
aa dd ee
dfs dfs dfs
运行结果:

总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
