python_文件操作
# 文件操作 ''' # 条件: 文件名称: 档案.txt 路径:D:\档案.txt 编码方式:utf-8 操作方式:读、写、追加、读写、写读.......... 以什么编码方式储存的,就要以什么编码方式操作 # 文件只读 :r # open('d:\档案.txt',mode = 'r',encoding='utf-8') 这是一个对象 f = open('d:\档案.txt',mode = 'r',encoding='utf-8') # 把这个对象赋给f # f.read # 这个对象的操作 一次性读出来,文件太大的话容易占满内存 h = f.read() # 把这个对象操作赋给h print(h) # 打印出 f.close() # 注:mode = 'rb' 时可以不加编码方式 它是以bytes二进制的形式打开文件,处理非文字的文件 # 文件只写 w 如果有这个文件会将源文件内容清空了,在写;没有会创建一个写 f = open('d:\log.txt',mode='w',encoding='utf-8') f.write("我是里面的内容") f.close() 如果是wb 二进制方式写入 f = open('d:\log.txt',mode='wb') # 可以不加编码方式 f.write("我是里面的内容".encode('utf-8')) # 写入的时候要加encode f.close() # 文件追加 f = open('d:\档案.txt',mode='a',encoding='utf-8') f.write("我是里面的内容") f.close() # ab 二进制方式 f = open('d:\档案.txt',mode='ab') f.write("我是里面的内容".encode('utf-8')) f.close() # r+ 模式下 读写 f = open('d:\档案.txt',mode='r+',encoding='utf-8') print(f.read()) # 只能读出原文章,光标定位原文章后面写入新文章 f.write('hello world') f.close() # r+ 读写 f = open('d:\档案.txt',mode='r+',encoding='utf-8') f.write('hahahahaha') # 光标会直接定位到最开始,写入的新文章会覆盖掉原文章 print(f.read()) f.close() # r+b # 以bytes类型 就是二进制 f = open('d:\档案.txt',mode='r+b') print(f.read()) f.write('hello world'.encode('utf-8')) f.close() # w+ 写读 f = open('d:\档案.txt',mode='w+',encoding='utf-8') f.write('hhhhhhh') f.seek(0) # 把光标调到0的位置 print(f.read()) f.close() # w+b 不在阐述 # a+ 追加读 f = open('d:\档案.txt',mode='a+',encoding='utf-8') f.write('eeeee') f.seek(0) print(f.read()) # 如果a不加+,f.read() 是无效的 f.close() # 功能详解 f = open("d:\档案.txt",mode="r+",encoding='utf-8') print(f.read(2)) # 可以去定位去读,单位是字符 f.seek(2) # 是按照字节定光标位置 print(f.tell()) # 获取光标当前的位置 f.close() # 我只想读后三位 调节光标读取 光标->文件指针 f = open('d:\档案.txt',mode='a+',encoding='utf-8') f.write('lkj') count = f.tell() # 找到光标位置,肯定在最后一位 print(count) print(type(count)) f.seek(count-7) # 然后指定光标到某个位置
f.readable() # 是否可读 返回flase true f.readline() # 一行一行读 缺点 不知道在哪结束 f.readlines() # 每一行当成列表中的一个元素,添加到list中 也是一次性读完 缺点 文件太大的话 容易占满内存 f.truncate() # 对原文件进行截取 print(f.read()) f.close() # 想看一个文件内容 for循环打印出来 f = open('d:\档案.txt',mode='r+',encoding='utf-8') # r+ 是比较常用 因为他也能追加 for line in f: print(line) f.close() # 有时候读的时候忘记最后关闭文档,忘写.close 下面这个自动读取关闭 with open('d:\档案.txt',mode='r+',encoding='utf-8') as f: print(f.read()) # 也可以多行去操作 with open('d:\档案.txt',mode='r+',encoding='utf-8') as f,\ open('d:\log.txt',mode='w+',encoding='utf-8') as h: print(f.read()) '''
# 文件修改 # 文件是不能修改的 # 要想修改 只能读 重新写 然后把以前的删掉 # 打开方式mode不写默认是r, with open('学习.py',encoding='utf-8') as f,\ open('学习.bak','w',encoding='utf-8') as f2: for i in f: if '嘿嘿嘿' in i: i = i.replace('嘿嘿嘿','hello') # 写文件 f2.write(i) import os os.remove('学习.py') # 删除文件 os.rename('学习.bak','学习') # 重命名文件