python(6)之文件

以追加文件内容(a)、读(r)、写(w),读写(r+)的形式打开文件:

  f = open('yesterday','a',encoding='utf-8')#文件句柄

#输出一行文件内容:
f.readline()
输出文件内容:

count=0
for lines in f:
print(lines)
count += 1
if count==9:
print('分隔符'.center(50,'-'))
continue
#将光标放在特定位置
f.seek(20)
#输出光标位置
f.tell()
#截断文件内容,以w方式打开文件
f.truncate(20)
f=open('yesterday','r+',encoding='utf-8')
print(f.readline())
f.seek(10)#光标移动10个字符后
f.tell()#打印光标位置
f.write('1111111111')#在光标后输入内容,但会覆盖原来文件里面该位置的内容
f=open('yesterday','rb')#文件句柄,二进制文件读
print(f.readline())'''
f=open('yesterday','wb')#文件句柄,二进制文件写
f.write('hello'.encode())
#关闭文件
f.close()

猜你喜欢

转载自www.cnblogs.com/aiyamoer/p/8946705.html