Python 文件操作(二)

来源:互联网 发布:淘宝历史版本 编辑:程序博客网 时间:2024/05/16 17:40

简介

文件的读写刷新操作,基本的命令总结如下表:

命令 说明 r 只读(默认) r+ 读写 w 写入 先删除原文件,再重新创建,如果文件不存在则创建 w+ 读写 先删除原文件,再重新创建,如果文件不存在则创建,可以写入输出 a 写入 在文件末尾追加新的内容,文件不存在,则创建 a+ 读写 在文件末尾追加新的内容,文件不存在,则创建 b 打开二进制的文件,可与r,w,a,结合使用 u 支持所有换行符号 \r\n

简单示例

#14f = open("yesterday2", 'r', encoding='utf-8')print(f.tell())print(f.readline())print(f.tell())f.seek(0)#返回光标print(f.readline())print(f.encoding)#编码方式print(f.fileno())#文件端口print(dir(f.buffer))f.close()

缓冲输出刷新:

import sysimport timefor i in range(50):    sys.stdout.write("#")    sys.stdout.flush()    time.sleep(0.1)

预先判断文件是否存在

如果文件存在,就报错;否则,创建并写内容

with open('database','x',encoding='utf-8') as f:    for line in f :        print(line)

FileExistsError: [Errno 17] File exists: ‘database’

文件既能读又能写

#读写f=open('D:/2345Downloads/yesterday2','r+',encoding='utf-8')#既能读又能写print(f.readline())print(f.readline())print(f.readline())print(f.tell())f.write('=====================')#只能在最后追加print(f.readline())
#写读f=open('D:/2345Downloads/yesterday2','w+',encoding='utf-8')#既能读又能写f.write('--------data--------\n')f.write('--------data--------\n')f.write('--------data--------\n')f.write('--------data--------\n')print(f.tell())f.seek(20)print(f.tell())f.write('=====================')#只能在最后追加print(f.readline())f.close()

文件的修改与新建

方法1、

f = open('D:/2345Downloads/yesterday2', 'r', encoding='utf-8')  #f_new = open('D:/2345Downloads/yesterday2.bak', 'w', encoding='utf-8')  #for line in f:    if "甜美的曲儿等我歌唱" in line:        line = line.replace("甜美的曲儿等我歌唱", "甜美的曲儿等Alex歌唱")    f_new.write(line)f.close()f_new.close()

方法2、

with open('D:/2345Downloads/yesterday2', 'r', encoding='utf-8') as f, \        open('D:/2345Downloads/yesterday2.bak', 'w', encoding='utf-8') as f_new:    for line in f:        if "甜美的曲儿等我歌唱" in line:            line = line.replace("甜美的曲儿等我歌唱", "甜美的曲儿等Alex歌唱")        f_new.write(line)

方法3、

with open("F:\\objectmarker\\neg\\sample_neg.dat",'r',encoding='utf-8') as f1,\    open("F:\\objectmarker\\neg\\new_sample_neg.dat",'w',encoding='utf-8')as f2:    total_sum = 0#用于计数    for line in f1:       str_line = line.split(" ")[:-2]       str_line.append('w')       str_line.append('y')       total_sum += int(str_line[1])       print(str_line)    print(" ".join(str_line))    print("count_pos_number:",total_sum)

这里写图片描述

二进制文件读取

f=open('D:/2345Downloads/yesterday','rb')#读取二进制文件,不用encoding,如视频、网络传输用途print(f.tell())print(f.readline())print(f.readline())print(f.tell())f.close()
f=open('D:/2345Downloads/yesterday','wb')#写二进制文件,需要encodingf.write('hahaha'.encode())f.close()
f=open('D:/2345Downloads/yesterday','ab')#追加二进制文件,需要encodingf.write('\nhello'.encode())f.close()

truncate文件的截断

利用f.seek()指定位置,光标位置之后清空了内容。
内容:

Admin|123456Alex|123Daisy|888888AlexTim|111Kevin|999OKokok
with open("database", "r+")as f:    for line in f:        if "999" in line:            print(line)    print(f.tell())    f.seek(64)    f.truncate()

执行后:
这里写图片描述

原创粉丝点击