温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

文件操作with语句

发布时间:2020-06-29 13:17:44 来源:网络 阅读:492 作者:坚持和学习 栏目:编程语言

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) #执行完自动关闭文件

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI