Python3搜索及替换文件中文本的方法,
Python3搜索及替换文件中文本的方法,
本文实例讲述了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程序设计有所帮助。
相关内容
- Python3实现从文件中读取指定行的方法,
- Python中的ctime()方法使用教程,pythonctime
- 在Python中操作日期和时间之gmtime()方法的使用,pythong
- Python中的localtime()方法使用详解,pythonlocaltime
- 在Python中操作时间之mktime()方法的使用教程,pythonmkti
- Python3读取UTF-8文件及统计文件行数的方法,
- Python3处理文件中每个词的方法,
- python实现数组插入新元素的方法,python新元素
- python实现的简单抽奖系统实例,python抽奖实例
- linux下python抓屏实现方法,python抓屏
评论关闭