文件操作

一 读

1. r模式 只读

f = open('t1',mode = 'r',encoding = 'utf-8')

f -- 文件句柄 所有对文件的操作都是操作文件句柄

第一个内容是文件的路径,必须是字符串)

第二个内容(mode)是对这个文件的操作方式 可以直接写'r'

第三个内容(encoding)是这个文件的编码集

f = open('t1',mode = 'r',encoding = 'utf-8')
print(f.read())
f.close()  # 打开文件最后要关闭文件
with open('t1',mode = 'r',encoding = 'utf-8')as f:     #上下文管理,不用后自动关闭   as后是变量名
    print(f.read())
  1. f.read() 一次性全部读取 ()里放数字,按照字符读取

    mode = 'r' read里的内容就是表示读取的字符数量

  2. f.readline() 只读一行,但是有个\n换行

    mode = 'r' readline里的内容就是表示这一行读取的字符数量

  3. f.readlines() 读取一行一行的,存放在一个列表里

2. rb模式 读取字节

f = open('t1',mode = 'rb')
f = open('E:\Python学习笔记\Python学习手册',mode = 'rb')

f = open('E:\\Python学习笔记\\Python学习手册',mode = 'rb')

f = open(r'E:\Python学习笔记\Python学习手册',mode = 'rb') #   r 和\\都是转义
print(f.read())
f.close()

绝对路径:E:\Python学习笔记\Python学习手册

相对路径(推荐路径):相对本文件的路径

..\   返回上一级

repr() 显示数据的原生态

二 写

1. w 模式 覆盖写 在写之前先把之前的内容清空

f = open('t1',mode = 'w',encoding = 'utf-8')
f.write('我爱你')
f.flush()   # 刷新,防止遗漏
f.close()

w模式,如果文件不存在就新建一个

2. wb 模式

f = open('t1',mode = 'rb')
f1 = open('t1',mode = 'wb')
f1.write(f.read())
f.close()

3. a 模式 追加

f = open('t1',mode = 'a',encoding = 'utf-8')
f.write('我爱你')
f.close()

文件最后添加内容

w 只写,没有读的功能

三 可读可写

1. r+ 读+写 最常用

f = open('t1',mode = 'r+',encoding = 'utf-8')
print(f.read())
f.write('我爱你')
f.close()

先读后写

2. w+ 写+读

f = open('t1',mode = 'w+',encoding = 'utf-8')
f.write('我爱你')   #写完之后光标在最后
f.seek(0)    #移动光标到头
print(f.read())
f.close()

3. a+ 写+读 光标永远在最后

f = open('t1',mode = 'a+',encoding = 'utf-8')
f.seek(0)    #移动光标到头
f.write('我爱你')
print(f.read())
f.close()

四 其他操作

1. f.tell() 查看光标

with open('t1','r',encoding = 'utf-8')as f:     
    print(f.read())
    print(f.tell())  #查看光标 数的是字节

2. f.seek() 移动光标

()里为单数字,按字节移动

(0)为文件头部

()里为双数字

(0,0)为文件头部

(0,1)为当前位子

(0,2)为文件尾部

3. f.truncate() 截取 ()里为字节数

with open('t1','r',encoding = 'utf-8')as f:     
    print(f.read(3))
    f.truncate(9)    #截取,指定字节之后的内容清空

4. 文件重命名

import os
os.rename('t1','t2')  #吧t1改成t2

5. 更改文件内容

with open('t1','r',encoding = 'utf-8')as f,\
open('t2','a',encoding = 'utf-8')as f1:#创建一个新文件(\表示一行写不下换行)     
    msg = f.read()
    msg = msg.replace('1','2')
    f1.write(msg)
import os
os.remove('t1')
os.rename('t2','t1')

先创建一个新文件,然后读取原文件,更改内容写到新文件,删除原文件,后给新文件重命名

with open('t1','r',encoding = 'utf-8')as f,\
open('t2','a',encoding = 'utf-8')as f1:     
    for i in f:    #一行一行读取,相当于readline()
    i = i.strip().replace('1','2')
    f1.write(i)
import os
os.remove('t1')
os.rename('t2','t1')

当文件很大时,一行一行读取然后更改

posted on 2019-11-05 20:36  Lav3nder  阅读(195)  评论(0编辑  收藏  举报