文件操做-增改查

修改文件的两种方式:spa

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

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)

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

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. 第二种方法: 把一个文件内容读出来写到另外一个文件中,而后更名字utf-8

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+) rem

写文件:write()  writelines() it

3.读 :   read  seek  tell  class

相关文章
相关标签/搜索