python中对文件的操作方式-python 对文件的操作

#author FK

import sys,time

#使用w模式,会覆盖原来的文件,从头开始写

f=open("test.txt","w",encoding="utf-8")

f.write("我是一只小小小鸟!!! ")

f.write("我想飞的更高更高。 ")

f.close()

#使用r模式,只能读不能修改

f1=open("test.txt","r",encoding="utf-8")

print(f1.read())

f1.close()

#使用a+,可能追加及可读,注意都追加在文件尾追加

f2=open("test.txt","a+",encoding="utf-8")

#写读,先创建文件,再写再读

#f2=open("test.txt","w+",encoding="utf-8").

#读写,先打开文件,先可读再写

#f2=open("test.txt","r+",encoding="utf-8")

#以二进制格式读文件

#f2=open("test.txt","rb")

f2.write("this is the appending text1 ")

f2.write("this is the appending text2 ")

#打印操作系统中打印文件的个数

print("print open files number:",f2.fileno())

#打印文件中的光标的位置

print("before seek method ,print the f2.tell method:",f2.tell())

#将光标移动到0位置,从头开始读

f2.seek(0)

print("after seek method ,print the f2.tell method:",f2.tell())

#逐行读文件

line_count = 0

for f22 in f2:

if line_count == 0:

line_count +=1

continue;

print(f22,end="")

line_count +=1

#截断,从指定位置开始截断,不管从光标在什么位置,都是从头计算开始截断

f2.seek(300)

f2.truncate(30)

#打印进度条

print(" 打印进度条测试:")

for i in range(5):

sys.stdout.write("#")

time.sleep(1)

#flush

sys.stdout.flush()

#关闭文件

f2.close()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值