12、文件操作

文件操作

  1.读文件

  rb(r,读 read;b 二进制 binary)

  rt(r,读 read;t,文本 text)

  • 读文本文件
# 1.打开文件
f = open('info.txt',mode='rb')

# 2.读取文件
data = f.read()

# 3.关闭文件
f.close()

print(data)    #data是读取到二进制的数据,如果想转换成人能看的,需要decode转换
text = data.decode('utf-8')
print(text)
# 1.打开文件
f = open('info.txt',mode='rt',encoding='utf-8')

# 2.读取文件
data = f.read()

# 3.关闭文件
f.close()

print(data)    #读取到的数据已被转换成utf-8
  • 读取图片等非文本内容文件
f = open('a.png',mode='rb')
data = f.read()
f.close()

print(data)    #data是读取到的数据

  

  2.写文件

  wb(r,读 read;b 二进制 binary)

  wt(r,读 read;t,文本 text)

  • 写文本文件
# 1.写入文本
w = open('t1.txt',mode='wb')
# 2.写入内容
w.write('ccc'.encode('utf-8'))
# 3.关闭文件
w.close()
# 1.写入文本
w = open('t1.txt',mode='wt',encoding='utf-8')
# 2.写入内容
w.write('ccc')
# 3.关闭文件
w.close()
  • 写图片等文件
f1 = open('a1.png',mode='rb')
cont = f1.read()
f1.close()

f2 = open('a.png',mode='wb')
f2.write(cont)
f2.close()

  

  3.文件打开模式

  • 只读:r、rt、rb
    • 存在,读  
    • 不存在,报错  
  • 只写:w、wt、wb
    • 存在,清空再写
    • 不存在,创建再写  
  • 只写:a、at、ab【尾部追加】
    • 存在,尾部追加
    • 不存在,创建再写
  • 读写
    • r+、rt+,rb+,默认光标位置:起始位置
    • w+、wt+,wb+,默认光标位置:起始位置(清空文件)
    • a+、wb+,默认光标位置:末尾

  

  4.常见功能

  • 读相关操作

  读所有

f = open('info.txt',mode='r',encoding='utf-8')
data = f.read()
f.close()

f = open('info.txt',mode='rb')
data = f.read()
f.close()

  读n个字符(字节)

f = open('info.txt',mode='r',encoding='utf-8')
data = f.read(1)
f.close()

f = open('info.txt',mode='rb')
data = f.read(1)
f.close()

  readline,读一行

f = open('info.txt',mode='r',encoding='utf-8')
r = f.readline()
print(r)
f.close()

  readlines,读所有行,每行作为列表的一个元素

f = open('info.txt',mode='r',encoding='utf-8')
rl = f.readlines()
print(rl)
f.close()

  循环,读大文件(readline加强版)

f = open('info.txt',mode='r',encoding='utf-8')
for line in f:
    print(line)
f.close()
  • 写相关操作

  write,写

f = open('info.txt',mode='a',encoding='utf-8')
f.write('阿斯顿')
f.close()

f = open('info.txt',mode='ab')
f.write('安全卫士多'.encode('utf-8'))
f.close()

  flush,立即刷到硬盘

f = open('info.txt',mode='a',encoding='utf-8')
while True:
    f.write('阿斯顿')
    f.flush()
f.close()

  移动光标位置(字节)

f = open('info.txt',mode='a',encoding='utf-8')
f.seek(3)    #移动3个字节
f.write('阿斯达')
f.close()
#注意:在a模式下,调用write在文件中写入内容时,永远只能将内容写入到尾部,不会写到光标的位置。

  获取当前光标位置

f = open('info.txt',mode='r+',encoding='utf-8')
p1 = f.tell()
f.write('阿斯达')
f.close()

  上下文管理

with open('info.txt',mode='r+',encoding='utf-8') as f:
    data = f.read()
    print(data)

#python2.7+后,with又支持同时对多个文件的上下文管理
with open('info.txt',mode='r+',encoding='utf-8'),open('info.txt',mode='r+',encoding='utf-8') as f:
    data = f.read()
    print(data)

 

posted @ 2021-03-15 13:57  tonitaka  阅读(95)  评论(0)    收藏  举报