目录
Python读写文本文件
Python读写文本文件主要方法
Python读写文本文件常用的方法有:
- open():打开文本文件对象,模式中没有"b"
- f.close():关闭资源
- f.write():写入字符串
- f.read():读取字符串
- f.readline():读取一行
- f.readlines():读取多行
文本文件中不常用的方法有
- f.flush():主动刷新缓冲
- f.seek():移动到指定位置开始读取字符串
- f.tell():返回当前读取的位置
- f.writelines(sequence):将序列按多行写入文本文件
Python读写文本文件示例
示例程序如下
myfname="myfile.txt"
mystrlist=[]
with open(myfname,"w") as f:
f.write("hello111n") # 写入一行文本
with open(myfname,"r") as fd:
astr=fd.read() # 读取文件所有内容
print(astr)
with open(myfname,"a") as f:
f.write("hello222n") # 写入一行文本,追加
f.write("hello333n") # 写入一行文本,追加
with open(myfname,"r") as fd:
astr=fd.read() # 读取文件所有内容
print(astr)
with open(myfname,"r") as fd:
astr=fd.readline() # 读取文件第一行
print(astr)
astr=fd.readline() # 读取文件第二行
print(astr)
with open(myfname, "r") as fd:
bstr = fd.readline() # 读取文件第一行
while bstr: # 用循环控制读取各行数据
print(bstr)
mystrlist.append(bstr[:-1]) # 使用字符串切片方法截取数据
bstr = fd.readline()
with open(myfname,"r") as fd:
astrs=fd.readlines() # 读取文件所有
print(astrs)
print(mystrlist)
程序运行结果
C:UsershccmaAnaconda3python.exe E:/wkp01/p00/test01/atestpkg/t06.py
hello111
hello111
hello222
hello333
hello111
hello111
hello222
hello333
['hello111n', 'hello222n', 'hello333n']
['hello111', 'hello222', 'hello333']
Process finished with exit code 0
从最后两行结果可以看出,f.readline()和f.readlines()读取的数据有换行标志"n"。如果需要处理,可以使用字符串处理方法,比如切片方式。
Python文件读取中的size作用
read() 方法语法如下:
f.read([size])
说明:
size -- 从文件中读取的字节数,默认为 -1,表示读取整个文件。
readline() 方法语法如下:
f.readline([size])
说明:
size -- 从文件中读取的字节数。
size的作用主要在二进制文件读写时使用。文本文件一般逐行处理,并且结合str对象处理方法。
文本文件编码要保持一致
文本文件读写时需要指定一致编码,否则会出现乱码。
示例程序如下
myfname="bfile.txt"
with open(myfname,"w",encoding="utf-8") as f: # 写文件时指定编码为utf-8
f.write("hello北京")
with open(myfname,"r",encoding="utf-8") as fd: # 读文件时指定编码为utf-8
astr=fd.read()
print(astr)
运行结果
C:UsershccmaAnaconda3python.exe E:/wkp01/p00/test01/atestpkg/t06.py
hello北京
Process finished with exit code 0