python修改文件

文档username.txt

将文件中密码123456改成67890:

方法一:(简单粗暴)

  1.打开文件

  2.读出数据

  3.修改数据

  4.清空原来文件,将新的内容写进去

f = open('username','a+')

f.seek(0)

all_str = f.read()

new_str = all_str.replace('123456','67890')

f.seek(0)

f.truncate()  #清空文件

f.write(new_str)

f.colse()

方法二:(简单高效)

思路:

  1.打开一个文件a

  2.写一行写到b文件

  3.a.txt   a.txt.bat

  4.删掉a文件,b文件名字改成a文件名

将文件中‘笔记’替换为‘BiJi’

import os   #导入os模块

with open('words.txt') as fr,with open('.words.bak','w') as fw:

  for line in fr:

    new_line = line.replace('笔记','BiJi')

    fw.write(new_line) 

os.remove('words.txt')   #删除文件

os.rename('.words.bak','words.txt')   #改名

 

posted @ 2018-04-17 13:34  我已不爱凯蒂  阅读(153)  评论(0编辑  收藏  举报