python 读取文件并替换字段的实例
作者:乌鸦来袭 时间:2022-10-18 05:12:21
如下所示:
fp = open(''test2.txt','w') #打开你要写得文件test2.txt
lines = open('test1.txt').readlines() #打开文件,读入每一行
for s in lines:
fp.write( s.replace('love','hate').replace('yes','no')) # replace是替换,write是写入
fp.close() # 关闭文件
import os
import re
f_path = r'c:\a.txt'
f = open (f_path, "r+")
open('c:\\test.txt', 'w').write(re.sub(r'hello world', 'Love python', f.read()))
原文:
参考备忘,指针这个没明白什么意思,找时间验证下
#写在原文件中
fp3=open("file3.txt","r+") #不用w w会清空数据
s=fp3.read()#读出
fp3.seek(0,0) #指针移到头 原来的数据还在是替换 会存在一个问题 如果少 会替换不了全部数据,自已思考解决!
#从头写入
fp3.write(s.replace("hello","good"))
fp3.close()
import os
os.chdir('D:\\') # 跳到D盘
if not os.path.exists('test1.txt'): # 看一下这个文件是否存在
exit(-1) #不存在就退出
lines = open('test1.txt').readlines() #打开文件,读入每一行
fp = open(''test2.txt','w') #打开你要写得文件test2.txt
for s in lines:
# replace是替换,write是写入
fp.write( s.replace('love','hate').replace('yes','no'))
fp.close() # 关闭文件
来源:https://blog.csdn.net/istend/article/details/53141349
标签:python,读取,文件,替换
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Flask框架踩坑之ajax跨域请求实现
2023-12-25 01:28:02
![](https://img.aspxhome.com/file/2023/3/80703_0s.png)
Python统计列表元素出现次数的方法示例
2021-03-06 00:43:23
Python 的第三方调试库 pysnooper 使用示例
2022-09-22 09:19:39
使用Python AIML搭建聊天机器人的方法示例
2022-01-04 10:14:28
php隐藏IP地址后两位显示为星号的方法
2023-08-16 13:05:17
体验DW MX 2004 CSS新功能
2011-06-14 09:45:01
![](https://img.aspxhome.com/file/UploadPic/20072/20072311321567s.gif)
Python列表去重复项的N种方法(实例代码)
2023-06-27 16:00:20
![](https://img.aspxhome.com/file/2023/0/60710_0s.jpg)
对numpy中数组元素的统一赋值实例
2021-05-31 18:47:37
python中实现栈的三种方法
2023-02-10 18:17:14
JavaScript中利用各种循环进行遍历的方式总结
2024-04-17 10:10:36
使用python开发vim插件及心得分享
2023-11-22 11:30:32
![](https://img.aspxhome.com/file/2023/2/70052_0s.gif)
详解如何用SQLyog来分析MySQL数据库
2008-10-13 12:35:00
![](https://img.aspxhome.com/file/UploadPic/200810/13/SQLyog-mysql_15s.jpg)
python解决OpenCV在读取显示图片的时候闪退的问题
2022-04-16 16:29:48
![](https://img.aspxhome.com/file/2023/9/72159_0s.jpg)
python pyaudio音频录制的实现
2022-03-13 08:44:31
![](https://img.aspxhome.com/file/2023/8/115758_0s.png)
解决Jstree 选中父节点时被禁用的子节点也会选中的问题
2023-09-03 06:56:01
![](https://img.aspxhome.com/file/2023/6/56186_0s.png)
python实现定时发送qq消息
2021-08-17 00:10:34
![](https://img.aspxhome.com/file/2023/1/109501_0s.jpg)
Python 按比例获取样本数据或执行任务的实现代码
2023-01-10 09:48:16
![](https://img.aspxhome.com/file/2023/6/115466_0s.png)
用户体验量化方法研究(二)
2010-02-08 12:46:00
SQL Server中row_number函数用法入门介绍
2024-01-26 22:45:04
![](https://img.aspxhome.com/file/2023/7/113527_0s.png)
javascript自定义加载loading效果
2024-04-27 15:23:14
![](https://img.aspxhome.com/file/2023/0/135500_0s.png)