Python3搜索及替换文件中文本的方法

yipeiwu_com7年前Python基础

本文实例讲述了Python3搜索及替换文件中文本的方法。分享给大家供大家参考。具体实现方法如下:

# 将文件中的某个字符串改变成另一个 
# 下面代码实现从一个特定文件或标准输入读取文件,
# 然后替换字符串,然后写入一个指定的文件 
import os, sys
nargs = len(sys.argv)
if not 3 <= nargs <= 5:
  print('usage: %s search_text repalce_text [infile [outfile]]' % \
     os.path.basename(sys.argv[0]))
else:
  search_text = sys.argv[1]
  replace_text = sys.argv[2]
  input_file = sys.stdin
  output_file = sys.stdout
  if nargs > 3:
    input_file = open(sys.argv[3])
  if nargs > 4:
    output_file = open(sys.argv[4], 'w')
  for s in input_file:
    output_file.write(s.replace(search_text, replace_text))
  output_file.close()
  input_file.close()

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

相关文章

python的常见命令注入威胁

ah!其实没有标题说的那么严重! 不过下面可是我们开发产品初期的一些血淋淋的案例,更多的安全威胁可以看看北北同学的《python hack》PPT,里面提及了不只命令执行的威胁,那些都是...

关于pandas的离散化,面元划分详解

pd.cut pandas.cut(x, bins, right=True, labels=None, retbins=False, precision=3, include_low...

Python使用matplotlib实现交换式图形显示功能示例

Python使用matplotlib实现交换式图形显示功能示例

本文实例讲述了Python使用matplotlib实现交换式图形显示功能。分享给大家供大家参考,具体如下: 一 代码 from random import choice import...

python实现简易数码时钟

python实现简易数码时钟

最近迷上了Python,要说为什么呢?Python语法简单,功能强大,有广泛的第三方库能快速编程实现自己的想法(无需重复去造轮子)。就像某位前辈说的:“人生苦短,学会偷懒…”,配置好su...

flask + pymysql操作Mysql数据库的实例

flask + pymysql操作Mysql数据库的实例

安装flask-sqlalchemy、pymysql模块 pip install flask-sqlalchemy pymysql ### Flask-SQLAlchemy的介绍...