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

yipeiwu_com6年前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操作oracle的完整教程分享

1. 连接对象 操作数据库之前,首先要建立数据库连接。 有下面几个方法进行连接。 >>>import cx_Oracle >>>db = cx_O...

使用matplotlib中scatter方法画散点图

使用matplotlib中scatter方法画散点图

本文实例为大家分享了用matplotlib中scatter方法画散点图的具体代码,供大家参考,具体内容如下 1、最简单的绘制方式 绘制散点图是数据分析过程中的常见需求。python中最有...

pygame游戏之旅 添加游戏暂停功能

pygame游戏之旅 添加游戏暂停功能

本文为大家分享了pygame游戏之旅的第13篇,供大家参考,具体内容如下 定义暂停函数: def paused(): largeText = pygame.font.SysFont...

python实现列表中最大最小值输出的示例

如下所示: def findMinAndMax(L): maxL = None minL = None if L: maxL = L[0] minL =...

Python父目录、子目录的相互调用方法

Python父目录、子目录的相互调用方法

最近在使用Python的过程中经常遇到找不到该模块的问题。其中一个就是父目录子目录之间相互调用的情况。下面简单总结下。 我们在F:\Code文件夹下面创建一个test文件夹 而test...