'''
二进制格式读写文件时,不能使用encoding='utf-8’参数,因为二进制文件不是以文本形式存储的,而是以字节流的形式存储的。在二进制文件中,每个字节都可以表示为一个整数值,而不是字符
在二进制模式下,我们可以使用read()方法读取字节流,并使用write()方法写入字节流
在二进制模式下,我们处理的是字节流而不是字符。因此,在读取或写入二进制文件时,我们不需要指定编码方式
'''
file = r"E:\Code\study_test\test.txt"
with open(file, "r+", encoding='utf-8') as files:
files = files.write("橙加冰")
print("返回值是寫入內容的長度",files)
with open(file,"r", encoding='utf-8') as files:
files = files.readlines()
print(files)
with open(file, "rb") as files:
files = files.readlines()
print(files)
with open(file, "rb+") as files:
files = files.readlines()
print(files)
with open(r"E:\Code\study_test\test_w.txt", "w", encoding='utf-8') as files:
files = files.write("橙加冰")
with open(r"E:\Code\study_test\test_wb.txt", "wb") as files:
files = files.write("橙加冰".encode("utf-8"))
with open(r"E:\Code\study_test\test_w+.txt", "w+", encoding='utf-8') as files:
files = files.write("橙加冰")
with open(r"E:\Code\study_test\test_wb+.txt", "wb+") as files:
files = files.write("橙加冰".encode("utf-8"))
with open(r"E:\Code\study_test\test_a.txt", "a", encoding='utf-8') as files:
files = files.write("橙加冰")
with open(r"E:\Code\study_test\test_ab.txt", "ab") as files:
files = files.write("橙加冰".encode("utf-8"))
with open(r"E:\Code\study_test\test_a+.txt", "a+", encoding='utf-8') as files:
files = files.write("橙加冰")
with open(r"E:\Code\study_test\test_ab+.txt", "ab+") as files:
files = files.write("橙加冰".encode("utf-8"))
with open(file,"r", encoding='utf-8') as files:
print("read:",files.read(3))
with open(file, "r", encoding='utf-8') as files:
print("readline:", files.readline())
with open(file, "r", encoding='utf-8') as files:
print("readlines:",files.readlines())
with open(file, "w", encoding='utf-8') as files:
'''write()需要传入一个字符串做为参数,否则会报错
writelines()既可以传入字符串又可以传入一个字符序列,并将该字符序列写入文件'''
files.writelines("\n202402020632\n\t202402020632\n")
print("mode:",files.mode)
print("encoding:",files.encoding)
print("name:",files.name)