手机
当前位置:查字典教程网 >脚本专栏 >python >Python3搜索及替换文件中文本的方法
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迭代器的使用方法实例

Python中针对函数处理的特殊方法

python切换hosts文件代码示例

Python常见文件操作的函数示例代码

Python中使用中文的方法

python逐行读取文件内容的三种方法

Python获取当前时间的方法

Python 字符串操作方法大全

Python转码问题的解决方法

python实现dnspod自动更新dns解析的方法

精品推荐
分类导航