zoukankan      html  css  js  c++  java
  • 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')   #改名

  • 相关阅读:
    计算机网络第一章_20210512
    bootloader_华清远见
    C#3.17
    linux--cd命令
    国内的开源网站
    安装linux
    如何自我介绍
    课堂破冰游戏“猜猜他是谁”
    办公软件---word
    计算机网络--技能训练
  • 原文地址:https://www.cnblogs.com/fancyl/p/8864506.html
Copyright © 2011-2022 走看看