文件操作-增改查

修改文件的两种方式:

1. 第一种方法:在原文件中修改: 先打开文件,把文件内容读出来赋值给一个变量,关闭文件,重新打开文件,把文件内容写到文件中

with open(r'f','r',encoding='utf-8')as f:
    data = f.read()
    print(data)
    print(type(data))

with open(r'f','w',encoding='utf-8')as f:
    res = data.replace('爱情','for love')
    f.write(res)

错误方法:同时以两种模式打开文件

with open(r'f','r',encoding='utf-8')as rf,\
        open(r'f','a',encoding='utf-8')as wf:
    data = rf.read()
    print(data)
    res = data.replace('爱情', 'for love')
    wf.seek(0,0)
    wf.write(res)

2. 第二种方法: 把一个文件内容读出来写到另一个文件中,然后改名字

import os

with open(r'b.txt','r',encoding='gbk')as rf,\
        open(r'b_wap.txt','w',encoding='gbk')as wf:
    data = rf.read()
    res = data.replace('穆斯林', '亚峰牛批')
    wf.write(res)

os.remove('b.txt')
os.rename('b_wap.txt','b.txt')

 

  

2.增 :创建文件(w,w+, a, a+) 

写文件:write()  writelines()   writealbe()          注意:写没有一行一行写,写多行writelines 带\n    或者for line in f  的形式 先读后写   详见随笔文件修改

3.读 :   read  seek  tell  

 读文件  read()  readline()  readable()     readline() 读一行  如果while 循环  光标会循环读

posted @ 2019-11-09 23:26  躺云飘  阅读(128)  评论(0编辑  收藏  举报