文件(读\写)操作
open()函数,用来打开文件,创建file对象。
open(name[,mode[,buffering]])
name:要打开的文件
mode:是打开文件的模式(读、写、追加)
buffering:是否要寄存,默认为0或者False(不寄存),1或True表示寄存(意味着使用内存来代替硬盘,让程序更快,只有使用flush或者close才会更新硬盘上的数据),如果大于1表示寄存区的缓冲大小(单位:字节),如果是负值,表示寄存区为系统默认大小。
open函数中模式参数的常用量:
r 读模式
w 写模式
a 追加模式
b 二进制模式(可添加到其次模式中使用)
+ 读/写模式(可添加到其他模式中使用)
例如:
r:读模式
f=open("D:\\test.txt",'r')
for i in f:
print i
f.close() #关闭文件
运行结果:
12345 abc
654321
[Finished in 0.1s]
w:写模式
def f_read():
f_r=open("D:\\test.txt",'r')
for i in f_r:
print i
f_r.close()
f_w=open("D:\\test.txt",'w') #写模式,非追加模式,新写入的内容将覆盖原有数据
f_w.write("welcome python")
f_w.close()
f_read()
运行结果:
welcome python
[Finished in 0.2s]
a:追加模式
def f_read():
f_r=open("D:\\test.txt",'r')
for i in f_r:
print i
f_r.close()
f_w=open("D:\\test.txt",'a') #写模式,追加模式,保留原有数据,新写入的数据放到原始数据后面
f_w.write("welcome python")
f_w.close()
f_read()
运行结果:
123456
798456welcome python
[Finished in 0.1s]
file对象的常用属性:
mode 返回被打开文件的访问模式
name 返回被打开文件的文件名
softspace 如果print输出后,必须跟一个空格符,则返回false,否则返回true
例如:
f_w=open("D:\\test.txt",'a')
f_w.write("welcome python")
print f_w.mode #打印file对象的模式
print f_w.name #打印file对象的文件名称
print f_w.softspace #是否强制在末尾加空格符
f_w.close()
运行结果:
a
D:\test.txt
0
[Finished in 0.2s]
file对象的常用方法:
read 读取文件内容
write 写入文件内容
close 关闭文件
tell 获取当前指针在文件的位置
seek 设置指针位置
read([count])方法,count表示要读取的长度,如果不传则读取全部内容
f_r=open("D:\\test.txt",'r')
print f_r.read()
运行结果:
123456
798456welcome pythonwelcome pythonwelcome pythonwelcome python
[Finished in 0.2s]
设置读取长度:
f_r=open("D:\\test.txt",'r')
print f_r.read(20) #读取20个字符长度
运行结果:
123456
798456welcome
[Finished in 0.1s]
write(string)方法:
f_w=open("D:\\test.txt",'w')
f_w.write("this is write content") #写入内容
f_w.close()
f_r=open("D:\\test.txt",'r')
print f_r.read()
f_r.close()
运行结果:
this is write content
[Finished in 0.2s]
tell()方法
f_w=open("D:\\test.txt",'w')
f_w.write("this is write content") #读取20个字符长度
f_w.close()
f_r=open("D:\\test.txt",'r')
print f_r.read(6)
print f_r.tell() #打印当前指针的位置
f_r.close()
运行结果:
this i
6
[Finished in 0.2s]
seek(offset[,from])方法,offset变量表示要移动的字节数,from变量指定开始移动字节的参考位置
f_w=open("D:\\test.txt",'w')
f_w.write("this is write content") #读取20个字符长度
f_w.close()
f_r=open("D:\\test.txt",'r')
f_r.seek(6) #从第6个位置开始读取
print f_r.read()
f_r.close()
运行结果:
s write content
[Finished in 0.1s]