第四章文件操作

4.1文件的基本操作

obj = open('文件名',mode='模式',encoding='编码')
obj.write()
obj.read()
obj.close()

4.2打开模式

  1. r /w /a

  2. r+/w+/a+

  3. rb/wb/ab

4.3操作

  1. read(),全部读到内存

  2. read(1) 1代表1个字符,数字代表字符

obj = open("a.txt"),mode = 'r',encoding = 'utf-8')
data = obj.read(1) #1个字符
obj.close()
print()

        3.write(字符串/二进制)

obj = open("a.txt"),mode = 'w',encoding = 'utf-8')
obj.write('你好') #1个字节
obj.close()
print()
obj = open("a.txt"),mode = 'w',)
#obj.write('你好',encoding('utf-8') #1个字节
v = '你好',encoding('utf-8')
obj.write(v)
obj.close()
print()

      4.seek(光标字节位置),无论模式是否带b,都是按照字节进行处理,无论何种模式都是调到指定字节

obj = open("a.txt"),mode = 'r',encoding = 'utf-8')
obj.seek(3)#跳转到指定字节位置
data = obj.read()
obj.close()
print(data)
obj = open("a.txt"),mode = 'r')
obj.seek(3)#跳转到指定字节位置
data = obj.read()
obj.close()
print(data)

     5.tell 获取光标当前所在的字节位置

obj = open("a.txt"),mode = 'r')
obj.seek(3)
data = obj.tell()
print(data) #输出是3
obj.close()

     6.flush(强制将写在内存的东西刷到硬盘上)

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

4.4关闭文件

1.文艺青年

v = open("a.txt"),mode = 'a',encoding = 'utf-8')

v.close()

2.二逼(自动关闭with .....as)

with open("a.txt",mode = 'a',encoding = 'utf-8') as v:

       data = v.read()
#缩进中的代码执行完毕后,自动关闭文件

文件内容的修改

1.小文件修改

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)

2.大文件修改

f1 = open('a.txt',mode = 'r',encoding = 'utf-8') 
f2 = open('a.txt',mode = 'w',encoding = 'utf-8')
for line in f1:
    new_line = line.replace('飞沙''666')
    f2.write(new_line)
fl.close()
f2.close()

with open('a.txt',mode = 'r',encoding = 'utf-8') as f1,open('a.txt',mode = 'w',encoding = 'utf-8') as f2:
    for line in f1:
        new_line = line.replace('飞沙''666')
    f2.write(new_line)

 

posted @ 2020-03-19 16:54  炜琴清  阅读(106)  评论(0编辑  收藏  举报