Python实现文件中指定字符串替换的方法
本文介绍如何使用Python编写脚本实现文件中指定子串的替换功能。通过读取源文件并写入新文件,支持可选的备份参数,确保操作安全。文章提供了完整的代码示例及执行过程解析,适用于需要批量修改文本内容的场景。
本文详细介绍利用Python实现文件中指定内容替换的具体方法,供读者参考学习。
该Python程序的核心功能是:将文件内指定的子字符串替换为新的子字符串。
程序文件命名为file_replace.py,具体实现代码如下:
#!/usr/bin/env python
#_*_ coding:utf-8 _*_
import sys,os
if len(sys.argv)<4 or 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编程实践有所帮助。
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









