文件操作with语句

import sys

data=open("gc.txt","r",encoding="utf-8") #只能读取文件

data=open("gc.txt","w",encoding="utf-8") #写模式创建一个文件(如果文件名相同会覆盖掉)

data=open("gc.txt","a",encoding="utf-8") #只能在文件后面追加

print(data.readline()) #打印一行

print(data.readlines()) #打印成列表

for i in range(5):

print(data.readline())

'''
#low 方法 适合读小文件
for index,line in enumerate(data.readlines()):#取出下标和对应的值
if index==9:
print("----ooo----")
continue
print(line.strip())

#high bige 度一行覆盖一行,常用牛逼方法
count=0
for loo in data:
if count==4:
print('-----You will die-----')
count+=1
continue
print(loo)
count+=1
'''

#光标使用

f=open("gc.txt","r",encoding="utf-8")

print(f.tell())#打印光标当前位置

print(f.read(5)) #按字符读取

print(f.readline()) #按行读取

print(f.tell())

f.seek(0)#光标移动端指定位置

print(f.encoding)#打印所用字符编码

print(f.flush())#强制刷新

f.truncate(10)#截断,从开头开始截,光标移动后再截断没用,依然从头开始算。

#f=open("yesok2",'r+',encoding="utf-8")#文件句柄 读写,在最后追加
#f=open("gc.txt",'w+',encoding="utf-8")#文件句柄 写读,覆盖原文件(创建新文件)后写。只会在最后追加。文件观后再打开写入会覆盖
#f=open("yesok2",'a+',encoding="utf-8")#文件句柄 追加读写

f=open("yesok2",'rb') #文件句柄 以二进制读文件

f=open("yesok2",'wb') #文件句柄 以二进制写

f=open("yesok2",'ab') #文件句柄 以二进制追加

f.write("hello\n".encode()) #二进制写读

f.close

f=open("gc.txt","r",encoding="utf-8")

f1=open("gc1.txt","w",encoding="utf-8")

for line in f:

if "是挣扎的自由" in line:

line=line.replace("是挣扎的自由","有我无敌天下")

f1.write(line )

#f.close()
#f1.close()

#find_str=sys.argv[1]
#replace_str=sys.argv[2]
#for line in f:
#if find_str in line:
#line=line.replace(find_str,replace_str)
#f1.write(line)
#f.close()
#f1.close()

with语句

with open("gege",'r',encoding="utf-8") as f:
for line in f:
print(line) #执行完自动关闭文件

同时打开文件不建议这么写

with open("gege",'r',encoding="utf-8") as f,open("gege",'r',encoding="utf-8") as f:
pass

打开多个文件建议这么写

with open("gege",'r',encoding="utf-8") as f,\
open("gege",'r',encoding="utf-8") as f2:
for line in f:
print(line) #执行完自动关闭文件

转载于:https://blog.51cto.com/12992048/2174300

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值