文件操作-增改查

修改文件的两种方式:

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() 

3.读 :   read  seek  tell  

猜你喜欢

转载自www.cnblogs.com/bigbox/p/11828506.html