标签:enumerate 模式 保留 输出 open seek read ace import
1.
1.1
一个字节(bety / B)8位, 一位一个bit / b即比特。即 1KB=1024B , 1B=8b,计算机存储信息的最小单位,称之为位(bit,又称比特)
1.2 读取方式( "r" , 模式,只读且只能读一遍,默认‘r‘模式)
#with模块执行结束后,自动关闭文件
with open(‘yesterday‘,encoding=‘utf-8‘) as file_objict:#Windows默认编码gbk,所以申明打开编码方式 contents = file_objict.read() print(contents) >>3.1415926535 >> 8979323846 >>我喜欢踢足球
file_object = open(‘yesterday‘,‘r‘,encoding=‘utf-8‘).read()#文件句柄 print(file_object)
file_object.close()
file_object = open(‘yesterday‘,‘r‘,encoding=‘utf-8‘).readlines() for i in file_object: print(i.rstrip())#去掉右边空格
file_object.close()
只读前几行,或指定的几行
file_object = open(‘yesterday‘,‘r‘,encoding=‘utf-8‘) for index,line in enumerate(file_object.readlines()):#enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据下标和数据 if index == 2:#前两行,index的默认值是0 print("------")#第三行会被替换 continue print(line.strip())
截断,f.truncate(),只保留指定个数的元素,移动光标没用,还是从头截取
f = open("yesterday","a",encoding="utf-8") f.truncate(10)
rand()整个内容的一个字符串,也可以添加个数,返回具体几个字符
randline()返回下一行内容的字符串
readlines()整个文件的列表
f.tell() 把指标位置打印,一开始为0
f.seek(0)把指标返回到开始,也可返回具体多少字符
f.encoding 打印其编码方式,是以utf-8的形式打开的
f.flush() 刷新,可不缓存直接存
import sys ,time for i in range(20):#实时打印 sys.stdout.write("#")#标准输出 sys.stdout.flush() time.sleep(0.1)
如果文件过大,则使用readlines()则太慢
file_object = open(‘yesterday‘,‘r‘,encoding=‘utf-8‘) count = 0 for line in file_object: #file_object 已被变为迭代器,无法取下标 if count == 2: print("-----------") count += 1 continue print(line)#打印一行,删除一行,不在内存中 count += 1 file_object.close()
1.3 "w"模式,创建或清零,如果有原文件会被清零,谨慎操作
file_object = open(‘yesterday‘,‘w‘,encoding=‘utf-8‘)#原文件被清零 file_object.write("I see you \n") file_object.write("我站在")
1.4 "a" 模式,追加,只可以追加,不可读(相当于append)
file_object = open(‘yesterday‘,‘a‘,encoding=‘utf-8‘) file_object.write("\n3.1415926")
1.5 “r+”, "w+","a+","rb","wb",“rU”
r+ ,读和追加,只能在最后追加
w+,写读,是创建一个新文件吧,并写入,如果再写入,还是最后追加(不常用)
a+ ,追加 读 写,
rb ,以二进制文件读取
f = open("yesterday","rb") print(f.readline()) >>b‘I see you \r\n‘#bytes 类型
wb,创建一个新文件,如果有内容则清零,以二进制写入
f = open("yesterday","wb") f.write("hello\n".encode())#hello是字符串类型,要encode一下,转换成字节码类型
rU,读取时,可以将\r \n \r\n 自动转换成 \n ,常用与linux 与 windows 文件转换
1.6 替换
f = open("yesterday","r",encoding="utf-8") f_new = open("new","w",encoding="utf-8") for line in f : if "old" in line: line = line .replace("old","new") f_new.write(line)
f.close()
f_new.close()
with open("yesterday","r",encoding="utf-8") as f , open("new","w",encoding="utf-8") as f_new : for line in f : if "old" in line: line = line .replace("old","new") f_new.write(line
1.7 异常处理
file_name = input("请输入文件名:") try: with open(file_name,"r",encoding="utf-8") as f :#不 contents = f.read() words = contents.split() w_num = len(words) print("The file" + file_name +"has about " + str(w_num) + "\twords") except FileNotFoundError: msg = "对不起,这个文件" + file_name + "不存在" print(msg)
标签:enumerate 模式 保留 输出 open seek read ace import
原文地址:https://www.cnblogs.com/huiguizhe/p/11988581.html