文件处理练习题:https://blog.csdn.net/zhouzongxin94/article/details/117303943
该文章没有整理,仅限于个人学习记录用
一、正常读写
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Date : 2021/5/24
# @Name : ZhouZongXin
"""
"""
import os
PAth = os.path.dirname(__file__)
file = os.path.join(PAth, "test01.txt")
files = "hello world,\n" \
"我叫小明。"
def w():
with open(file, "w+", buffering=1) as f: # buffering=1 行缓冲,遇到换行则缓冲
data = f.read(5) # f.read(5)读取5个字节数据
print(data) # 输出写入内容
c = f.write(files) # 写入操作
print(c) # 打印总共写入了几个字节
def r():
f = open(file, "r+")
while True:
rf = f.readline()
if not rf: # 如果为假(空格)则退出循环
break
print(rf, end="")
f.close()
w()
r()
二、缓冲区及位置偏移量
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Date : 2021/5/26
# @Name : ZhouZongXin
"""
"""
import os
PAth = os.path.dirname(__file__)
file = os.path.join(PAth, "test01.txt")
f = open(file, 'wb+')
f.write(b"hello world")
f.flush() # 主动刷新缓冲区, f.flush(10)如果写10就是10个字节刷新一次
# 0:表示文件开头
# 1:表示当前位置
# 2:表示文件末尾
# 设置读取的偏移量位置(从末尾往前挪移2位),但是如果移动数为负数时,写入和读取的格式必须是byte格式
f.seek(-2, 2)
print("当前文件偏移量所在位置", f.tell()) # f.tell()查看当前偏移量的位置
data = f.read()
print(data)
f.close()