# python 文件处理 # /usr/sbin/py/python # -*-coding:utf8-*- inner = open("a/document.txt") # 这种方式打开的文件默认是读模式 eqInner = open("a/document.txt", "r") # 等同于上式 文件的打开模式 r:只读 w:只写 a:追加 print(eqInner.read()) eqInner.close() a = inner.read() print(a) inner.close() text = open("a/测试文件.txt", encoding="utf8") # 当文件名为汉语时需要指定编码 print(text.readline()) print(text.readline()) print("------------------>") innerText = text.read() print(innerText) # 同一个stream中文件内容读出去了,再读,就没有了 print(text.readable()) # 是否是可读的 r:true w:false text.close() winner = open("a/documentTest.txt", "w", encoding="utf8") # 写模式 如果文件存在会将文件中的内容清空然后再写入,不存在则创建 winner.write("hello ") winner.writelines("jake\n") winner.writelines("where is tom?") ainner = open("a/document.txt", "a", encoding="utf8") ainner.writelines("jake") rAndw = open("a/abc.txt", "r+", encoding="utf8") data = rAndw.read() print(data) rAndw.write("额") rAndw.close() with open("a/abc.txt", "r", encoding="utf8") as f: print(f.read()) # python 以字节的方式操作文件 f1 = open("a/字节.txt", "rb") data = f1.read() print(data.decode("utf8")) f2 = open("a/字节写入.txt", "wb") f2.write("jake".encode("utf8")) f2.write(bytes("tom", encoding="utf8")) f2.close() # python 测试回车 f3 = open("a/回车.txt", "r", encoding="utf8") print(f3.readlines()) f3.close() f4 = open("a/回车.txt", "r", encoding="utf8", newline="") # 不用python自动转换,自动输出 print(f4.tell()) # 获取读取位置 print(f4.seek(3)) # 跳过几个字符 print(f4.readlines()) # f4.truncate(10) # 截断 取前10个字节 f4.close() # seek 方法三种模式 f5 = open("a/seek.txt", "rb") f5.seek(-10, 2) # 2 表示倒着数十个字节 print(f5.tell()) print(f5.read()) f5.close() # 读取最后一行 f6 = open("a/seek.txt", "rb") data = f6.readlines() # 这样读虽然也能获取最后一行,但无用数据全部加载到了内存,性能极差 print(data) print(data[-1].decode("utf8")) f6.close() f7 = open("a/seek.txt", "rb") # 循环文件 for i in f7: # 这种取法用到才会加载到内存 offset = 10 while True: f7.seek(-offset, 2) data = f7.readlines() if len(data) > 1: print(data[-1].decode("utf8")) break else: offset *= 2