文件查询与修改

test的内容:
白日不到处,
青春恰自来。
苔花如米小,
也学牡丹开。

test1的内容:
hellopp王

test2的内容:
hello


# 修改一个文件
# with open("test",encoding="utf8") as f_read,open("test1",encoding="utf8",mode="w") as f_write :
# j = 1
# for i in f_read:
# if j==3:
# i="".join([i.strip(),"诗人 "])
# f_write.write(i)
# j+=1
#
# import os
#
# os.rename("test","test00")
# os.rename("test1","test")

# 显示进度条0% 或1% # 或2% ##
# import sys
# for i in range(101):
# s=" %d%% %s"%(i,"#"*i)
# # 就是把鼠标移到第一个位置,也就是覆盖之前的那些内容,
# # 是先移到第一个位置再移动下一行,也就是光标在下一行第一个位置
#
# sys.stdout.write(s)
# sys.stdout.flush() # 更新
#
# import time
# time.sleep(0.5)

# 读写追加模式
# f=open("test",mode="r",encoding="utf8")
# print(f.read(3))
# f.seek(0) # 这里如果把0改为别的数字就报错,跟test的内容有中文有关
# print(f.read(1))
# test1前面都是字母,看看seek能不能改别的数字
# f=open("test1",mode="r",encoding="utf8")
# print(f.read(3))
# f.seek(1)
# print(f.read(1))



# f.seek(1,2) # 2表示从最后开始取字节,既然是字节,mode就要改为rb
# f=open("test1",mode="rb")
# print(f.read(3))
# # f.seek(1,2) # 从最后开始取1个字节
# # print(f.read())
# f.seek(-10,2) # 从最后开始往前取10个字节(汉字王占3个字节)
# print(f.read())
# print(f.read().decode("utf8"))

f=open("test2",mode="wb+") # wb只能写,wb+可能有读
f.write(b"hello")
print(f.read())
f.seek(-1,2) # 从最后开始往前取1个字节
print(f.read())


原文地址:https://www.cnblogs.com/jensenxie/p/8457756.html