• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

Python实现替换文件中指定内容的方法

python 搞代码 4年前 (2022-01-07) 26次浏览 已收录 0个评论

这篇文章主要介绍了Python实现替换文件中指定内容的方法,涉及Python文件读写、字符串替换等相关操作技巧,需要的朋友可以参考下

本文实例讲述了Python实现替换文件中指定内容的方法。分享给大家供大家参考,具体如下:

这里使用python编写的程序,实现如下功能:将文件中的指定子串 修改为 另外的子串

编写的python程序,文件名是file_replace.py,具体代码如下:

 #!/usr/bin/env python #_*_ coding:utf-8 _*_ import s<div style="color:transparent">来源gaodai.ma#com搞##代!^码@网</div>ys,os if len(sys.argv)5: sys.exit('There needs four or five parameters') elif len(sys.argv)==4: print 'usage:./file_replace.py old_text new_text filename' else: print 'usage:./file_replace.py old_text new_text filename --bak' old_text,new_text=sys.argv[1],sys.argv[2] file_name=sys.argv[3] f=file(file_name,'rb') new_file=file('.%s.bak' % file_name,'wb')#文件名以.开头的文件是隐藏文件 for line in f.xreadlines():#f.xreadlines()返回一个文件迭代器,每次只从文件(硬盘)中读一行 new_file.write(line.replace(old_text,new_text)) f.close() new_file.close() if '--bak' in sys.argv: #'--bak'表示要求对原文件备份 os.rename(file_name,'%s.bak' % file_name) #unchanged os.rename('.%s.bak' % file_name,file_name) #changed else: os.rename(file_name,'wahaha.txt')#此处也可以将原文件删除,以便下一语句能够正常执行 os.rename('.%s.bak' % file_name,file_name) 

下面是代码执行的一个例子:

 song@ubuntu:~$ more hello.txt Hello python Hello world python Hello world Hello song@ubuntu:~$ python file_replace.py Hello love hello.txt --bak usage:./file_replace.py old_text new_text filename --bak song@ubuntu:~$ ls Desktop Documents  file_replace.py Music systemExit.py diff1.txt Downloads  hello.txt Pictures Templates diff.txt examples.desktop hello.txt.bak Public Videos song@ubuntu:~$ more hello.txt love python love world python love world love song@ubuntu:~$ more hello.txt.bak Hello python Hello world python Hello world Hello song@ubuntu:~$ 

更多Python相关内容感兴趣的读者可查看本站专题:《Python字符串操作技巧汇总》、《Python编码操作技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》

希望本文所述对大家Python程序设计有所帮助。

以上就是Python实现替换文件中指定内容的方法的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:Python实现替换文件中指定内容的方法

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址