当前位置: 首页 > article >正文

Python小程序 - 替换文件内容

    1. 写入文件c:\a.txt
        1)共写入10行
        2)每行内容 0123456789

# 1
ls = '0123456789'
ln = 10
with open("c:/a.txt", 'w+',encoding='UTF-8') as f:
    for i in range(ln):
        f.write(ls+'\n')

########################################

# 2
ln = 10
with open("c:/a.txt", 'w+',encoding='UTF-8') as f:
    for i in range(ln):
        ls = str(i)
        for j in range(ln):
            ls = ls + str(j)
        f.write(ls+'\n')

##
00123456789
10123456789
20123456789
30123456789
40123456789
50123456789
60123456789
70123456789
80123456789
90123456789

    2. 替换文件内容
       1)全文替换指定内容

# replace '1' with 'a'

# 1
with open("c:/a.txt", 'r',encoding='UTF-8') as f:
    fl = f.readlines()

    for fs in fl:
        print(fs.replace('1','a'))
        
###############################################

# 2-1
with open("c:/a.txt", 'r',encoding='UTF-8') as f:
    fl = f.readline()

    while fl:
        print(fl.replace('1','a'))
        fl = f.readline()

# 2-2
fl = ''
with open("c:/a.txt", 'r',encoding='UTF-8') as f:
    fl = f.readlines()

    for fn in range(len(fl)):
        print(fl[fn].replace('1','a'))
        fl[fn] = fl[fn].replace('1','a')
        print(fl[fn])

with open("c:/a.txt", 'w',encoding='UTF-8') as f:
    f.writelines(fl)

####
00a23456789
a0a23456789
20a23456789
30a23456789
40a23456789
50a23456789
60a23456789
70a23456789
80a23456789
90a23456789

      2)替换指定行的内容

# replace line 5
# replace '1' with 'A'
rl = 5
rw = 'A'
with open("c:/a.txt", 'r',encoding='UTF-8') as f:
    fl = f.readlines()

    fl[rl-1] = fl[rl-1].replace('1',rw)

with open("c:/a.txt", 'w',encoding='UTF-8') as f:
    f.writelines(fl) 

##
00123456789
10123456789
20123456789
30123456789
40A23456789
50123456789
60123456789
70123456789
80123456789
90123456789

    3. 定义函数 
 

def replace_word_in_file(file_path,old_word,new_word,line_num):
    fl = '' # file content
    
    with open(file_path, 'r',encoding='UTF-8') as f:
        fl = f.readlines()

        if(line_num>len(fl) or line_num<0 ):
            print('Wrong line number, pleae check.')
        # replace all in file              
        elif(line_num == 0):
            for fn in range(len(fl)):
                fl[fn] = fl[fn].replace(old_word,new_word)
        else:
            fl[line_num-1] = fl[line_num-1].replace(old_word,new_word)

    with open(file_path, 'w',encoding='UTF-8') as f:
        f.writelines(fl)


if __name__ == "__main__":
    replace_word_in_file("c:/a.txt",'1','A',0)  # 1  
    replace_word_in_file("c:/a.txt",'1','A',5)  # 2
    replace_word_in_file("c:/a.txt",'1','A',11) # 3
    replace_word_in_file("c:/a.txt",'1','A',-1) # 4

## 1
00A23456789
A0A23456789
20A23456789
30A23456789
40A23456789
50A23456789
60A23456789
70A23456789
80A23456789
90A23456789

## 2
00123456789
10123456789
20123456789
30123456789
40A23456789
50123456789
60123456789
70123456789
80123456789
90123456789

## 3
Wrong line number, pleae check.

## 4
Wrong line number, pleae check.

-- 创作助手提问

  1. python readline 逐行读出
    with open('file.txt', 'r') as file:
        line = file.readline()
        while line:
            print(line)
            line = file.readline()
  2. python 写入文件
    # 打开文件,以写入模式('w')进行操作
    file = open('example.txt', 'w')
    
    # 写入文本
    file.write('Hello, world!')
    
    # 关闭文件
    file.close()

http://www.kler.cn/news/362348.html

相关文章:

  • 【Vue3】将 Element Plus 引入 Vue3 项目
  • AWD的复现
  • vuex的store应用
  • 电机编码器
  • QT--文本框 QLineEdit、qtextedit
  • Nacos相关问题
  • Redis Search系列 - 第四讲 支持中文
  • 003:Context Capture10.16安装教程
  • Linux中如何理解一切皆文件
  • 【YOLO模型】(1)--YOLO是什么
  • Android 13 SPRD 如何临时修改 Android 系统版本
  • 开源模型应用落地-Qwen2.5-7B-Instruct与vllm实现离线推理-Tools助力(二)
  • w~自动驾驶合集9
  • RHCE笔记-SSH服务
  • 毕业设计项目系统:基于Springboot框架的网上订餐管理系统,完整源代码+数据库+毕设文档+部署说明
  • Spring Cloud --- Sentinel 授权规则
  • StarTowerChain:开启去中心化创新篇章
  • gitlab-cli无法构建流水线
  • 数据结构 - 树,初探
  • 最好的ppt模板网站是哪个?做PPT不可错过的18个网站!
  • 记录一个容易混淆的 Spring Boot 项目配置文件问题
  • 监控易-某信息化系统监控-监测点详情解读
  • Java学习教程,从入门到精通,Java 基本数据类型(7)
  • 【VUE】v-show 和 v-if 的区别
  • 11. 事件机制
  • FFmpeg源码:av_malloc_array、av_realloc_array函数分析