文件操作


文件操作

打开文件:
f = open("how.txt")

关闭文件:
f.close()


读文件:
f.read()


打开模式:
f = open("how.txt",'r')  #读
f = open("how.txt",'w')  #写,会清空原内容然后写入
f = open("how.txt",'a')  #追加
f = open("how.txt",'r+') #读写模式
f = open("how.txt",'w+') #写读模式,先清空,然后写,再读
f = open("how.txt",'a')  #追加写模式
f = open("how.txt",'rb') #二进制文件读模式


打印每一行:
f = open("how.txt",'r')

for line in f:
    print(line)

f.close()

##########

count = 0
for line in f:
    if count != 3:
       print(line)
    count += 1

回到某位置:
f.seek(0)
    
    
进度条:
import sys,time
for i in range(50):
    sys.stdout.write("#")
    sys.stdout.flush()
    time.sleep(0.1)
    
从某位置截断:
f.truncate(3)

with语句,可打开多个文件:
with open("how.txt",'r') as f:

with open("how.txt",'r') as f1,open("how2.txt",'r') as f2:






来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/26735168/viewspace-2131956/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/26735168/viewspace-2131956/

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值