python文件操作模式及文件指针移动

一、文件操作的模式

文件的打开模式分为两大类
一、控制文件读写操作的模式
1 、r:只读(默认的):在文件不存在时则报错,文件存在时文件指针跳到文件开头

f = open("a.txt",mode = "rt",encoding="utf-8")
res = f.read()

2、 w:只写,在文件不存在时则创建空文件,文件存在时则清空,文件指针跳到文件开头

f = open("b.txt",mode= "wt",encoding = "utf-8")
f.read()
f.close()

3 、a:只追加写在文件不存在时则创建空文件,文件存在时也不会清空,文件指针跳到文件末尾

f = open("c.txt",mode= "at",encoding = "utf-8")
f.write("\nmin:123")
f.close()

总结:w和a的
相同点:在打开了文件不关闭的情况下,连续写入,新的内容永远跟在老内容之后
不同点:重新打开文件,w会清空老的内容,而a模式会保留老的内容并且指针跳到文件末尾

二、控制文件读写内的模式
1、t:读写都是以str字符串为单位,一定要指定encoding

f = open("b.txt",mode="rt",encoding="utf-8")
f.read()
f.close()

2、b:读写都是以bytes为单位,一定不能指定encoding

f = open("b.txt",mode = "rb")
f.read()
f.close()

示范:copy文件

old_path = input("请输入原文件路径:").strip()
new_path = input("请输入新文件路径:").strip()
f = open("%s %old_path",mode = "rb")
data = f.read()
new_f = open("%s %new_path",mode = "wb")
f.write(data)
f.close()
new_f.close()

with上下文管理,自动回收,不用加f.close

old = input("请输入源文件路径:").strip()
new = input("请输入新文件路径:").strip()
with open("%s" %old,mode="rb") as f,open("%s" %new,mode="wb")as new_f:
    data = f.read()
    new_f.write(data)

用for循环

old = input("请输入源文件路径:").strip()
new = input("请输入新文件路径:").strip()
with open("%s" %old,mode="rb")as f ,open("%s" %new ,mode="wb")as new_f:
    for line in f:                     new_f.write(line)  

补充知识点:
“+” 表示可以同时读写某个文件
r+, 读写【可读,可写】
w+,写读【可读,可写】
a+, 写读【可读,可写】

“x” 只写模式【不可读;不存在则创建,存在则报错】
x+ ,写读【可读,可写】
xb

掌握
f.read() #读取所有内容,光标移动到文件末尾
f.readline() #读取一行内容,光标移动到第二行首部
f.readlines() #读取每一行内容,存放于列表中

f.write(‘1111\n222\n’) 针对文本模式的写,需要自己写换行符
f.write(‘1111\n222\n’.encode(‘utf-8’)) #针对b模式的写,需要自己写换行符
f.writelines([‘333\n’,‘444\n’]) 文件模式
f.writelines([bytes(‘333\n’,encoding=‘utf-8’),‘444\n’.encode(‘utf-8’)]) b模式

#了解
f.readable() 文件是否可读
f.writable() 文件是否可读
f.closed 文件是否关闭
f.encoding 如果文件打开模式为b,则没有该属性
f.flush() 立刻将文件内容从内存刷到硬盘
f.name()获取文件路径

二、控制文件指针移动

控制文件内指针的移动都是以字节为单位的
只有一种特殊情况,t模式下的read(n),代表的是n个字符,此外代表的全部是字节
f.seek(n,模式) n代表是移动的字符
模式:

0:参照文件的开头移动(只有0模式可以在t下使用,1和2模式只能在b模式使用)

# with open("tttttt.txt",mode="rt",encoding="utf-8")as f:
#     f.seek(5,0)
#     print(f.tell())
#     print(f.read())

print(f.tell()) # tell() 方法返回文件的当前位置,即文件指针当前位置。

1:参照指针当前所在的位置

# with open("tttttt.txt",mode="rb")as f:
#     f.seek(3,1)
#
#
#     print(f.tell())
#     print(f.read())

# 2:参照文件末尾位置

# with open("tttttt.txt", mode="rb")as f:
#     f.seek(0, 2)   #11
#     print(f.tell())
#     print(f.read())
# with open('f.txt',mode='rb') as f:
#     f.seek(0,2)      11
#     f.seek(-3,2)    #2模式下负数往左
#     # print(f.tell())
#     print(f.read().decode('utf-8'))
# with open("tttttt.txt",mode = "rb",)as f:
#     f.seek(2,2)       #2模式下光标往右多出2个空白字节,13
#     print(f.tell())
#     print(f.read())

日志

# import time
# 描述
# __import__() 函数用于动态加载类和函数 。
# 如果一个模块经常变化就可以使用 __import__() 来动态载入
# for i in range(1000000000):
#     with open('access.log',mode='at',encoding='utf-8') as f:
#         t=time.strftime("%Y-%m-%d %H:%M:%S")
#        time strftime() 函数接收以时间元组,并返回以可读字符串表示的当地时间,格式由参数format决定。
#         #某年某月某日某时某分某秒
#         content="egon给刘老师转了%s个亿" %i
#
#         msg=f"{t} {content}\n"
#         f.write(msg)
#     time.sleep(3)
# Python time sleep() 函数推迟调用线程的运行,可通过参数secs指秒数,表示进程挂起的时间
#



# import time
# with open("access.log",mode = "rb")as f:
#     f.seek(0,2)
#
#     while True:
#         line = f.readline()
#         if len(line) == 0:
#             time.sleep(0.5)
#     else:
#         print(line.decode("utf-8"),end="")
# #

监控

tail -f access.log程序实现
import time
with open('access.log',mode='rb')as f:
    f.seek(0,2)
    while True:
        line = f.readline()
        if len(line)==0:
            time.sleep(0.5)
        else:
            print(line.decode("utf-8"),end ="")

你可能感兴趣的:(笔记,编程)