1 # 打开文件 2 # f = open('d:\\a.txt', mode='r', encoding='gbk') 3 # content = f.read() 4 # print(content) 5 # f.close() 6 7 # 只读 8 # f = open('d:\\a.txt', mode='r', encoding='gbk') 9 # content = f.read()10 # print(content)11 # f.close()12 # bytes读写时,不用指定读写模式13 # f = open('d:\\a.txt', mode='rb')14 # content = f.read()15 # print(content)16 # f.close()17 18 # 写文件,没有创建一个,有的话清空文件,再写19 # f = open('d:\\b.txt', mode='w', encoding='gbk')20 # f.write('你好')21 # f.close()22 # # bytes写时23 # f = open('d:\\b.txt', mode='wb')24 # f.write('你好'.encode('utf-8'))25 # f.close()26 27 # 追加28 # f = open('d:\\b.txt', mode='a', encoding='gbk')29 # f.write('whats up')30 # f.close()31 # f = open('d:\\b.txt', mode='ab')32 # f.write('whats up'.encode('gbk'))33 # f.close()34 # 读写,先读后写,35 # 句柄操作,先读时,读完内容,句柄移到最后,再接着写入36 # 先写后读,先写入,然后最接着句柄往下进行读取内容37 f = open('d:\\b.txt', mode='r+', encoding='utf-8')38 print(f.read())39 f.write('123')40 f.close()41 # 写读 先写后读,会先清空 然后写42 f = open('d:\\b.txt', mode='w+', encoding='utf-8')43 print(f.read())44 f.write('123')45 f.close()46 # 寻找句柄 seek 方法 寻找句柄47 f = open('d:\\b.txt', mode='r+', encoding='utf-8')48 f.write('123')49 f.seek(0)50 print(f.read())51 f.write('123')52 f.close()53 # 读取的是字符54 f.read(3)55 # 读取的是字节56 f.seek(3)57 # 查看光标的位置58 f.tell()59 # 判断是否可读60 f.readable()61 # 一行一行读62 f.readline()63 # 将每一行读成列表中的一个列表的元素,添加到列表中64 f.readlines()65 # 是否可读66 f.writable()67 # 截取前两个字符68 f.truncate(2)69 # 文件循环70 for line in f:71 print(line)72 # with读取完,自动关闭文件73 with open('d:\\a.txt', mode='r', encoding='gbk') as obj1, \74 open('d:\\a.txt', mode='r', encoding='gbk') as obj2:75 print(obj1.read())