第四章.文件操作

时间:2020-11-29 22:12:15

4.1文件的基本操作

data = open('路径',mode='模式',encoding='编码')
data.read()
data.write()
data.close()

4.1.1只读只写字符串

  • r:只读,默认模式,文件不存在就报错

  • w:只写,文件存在就覆盖,文件不存在就创建

  • a:只追加,文件存在不覆盖,只会在已存在的内容后面追加,文件不存在就创建。

4.1.2可读可写字符串

  • r+:读:默认从0光标位置开始读,可通过seek函数调整光标位置

    写:从光标位置开始写,可通过seek函数调整光标位置(可能使文件被覆盖)

  • w+:写:写入时先清空文件

    读:默认光标位置永远位于写入的内容后面或者0位置,可通过seek函数调整光标

  • a+:读:默认光标位于最后,可通过seek函数调整光标位置

    写:永远位于文件最后

4.1.3只读只写二进制

  • rb

  • wb

  • ab

4.1.4可读可写二进制

  • r+b

  • w+b

  • a+b

4.2操作

4.2.1read

  • read(),全部读到内存

  • read(1)

    • 1表示一个字符

      data = open('a.txt',mode='r',encoding='utf-8')
      v = data.read(1)  #1表示一个字符
      data.close()
      print(v)
    • 1表示一个字节

      data = open('a.txt',mode='rb')
      v = data.read(1)  #1表示一个字节
      data.close()
      print(v)

4.2.2write

  • write(字符串)

    data = open('a.txt',mode='w',encoding='utf-8')
    data.write('xxxxxxx')   #‘'XXXXXX'为一个字符串
    data.close()
  • write(二进制)

    data = open('a.txt',mode='wb')
    v = 'XXXXX'.encode("utf-8")#就是data.write(“xxxx”。encode(utf-8))
    data.write(v)  
    data.close()

4.2.3seek

seek为光标字节位置,无论是否带b,都按照字节处理

obj = open('a.txt',mode='w',encoding='utf-8')
obj.seek(3)
data = obj.read()#就是将文件中内容读取到内存
obj.close()
print(data)
obj = open('a.txt',mode='rb')
obj.seek(3)
data = obj.read()
obj.close()
print(data)

4.2.4tell()

获取光标当前所在字节位置

obj = open('a.txt',mode='rb')
# obj.seek(3) #跳转到指定字节位置
obj.read()
data = obj.tell()
print(data)
obj.close()

4.2.5flush

强制将内存中的数据写入到硬盘

obj = open('a.txt',mode='w',encoding='utf-8')
while True:
   val = input('请输入:')
   obj.write(val)
   obj.flush()
obj.close()

4.3关闭文件

  • 第一种打开方式

    obj = open('a.txt',mode='w',encoding='utf-8')
    obj.close()
  • 第二种打开方式

    with open('a.txt',mode='a',encoding='utf-8') as v:
    data = v.read()
    #缩进中的代码执行完毕后,自动关闭文件

文件内容的修改

with open('a.txt',mode='r',encoding='utf-8') as f1:
data = f1.read()
   new_data = data.replace('飞洒','666')
with open('a.txt',mode='w',encoding='utf-8') as f1:
   data = f1.write(new_data)

大文件的修改

f1 = open('a.txt',mode='r',encoding='utf-8')
f2 = open('b.txt',mode='w',encoding='utf-8')
for line in f1:
   new_line = line.replace('阿斯','死啊')
   f2.write(new_line)
f1.close()
f2.close()
with open('a.txt',mode='r',encoding='utf-8') as f1, open('b.txt',mode='w',encoding='utf-8') as f2:
   for line in f1:
       new_line = line.replace('阿斯', '死啊')
       f2.write(new_line)