python3 实现类似sed修改文件功能

文山羊 2020-02-14

#! /usr/bin/env python3
# -*- encoding:utf-8 -*-

import sys,os


find_str = sys.argv[1]
replace = sys.argv[2]
file_name = sys.argv[3]
f1 = open(file=file_name,mode='r',encoding='utf-8')
f2 = open(file=file_name+'_new',mode='w',encoding='utf-8')
for item1 in f1:
    if 'first' in item1:
        item1 = item1.replace(find_str,replace)
    f2.write(item1)
f1.close()
f2.close()

os.remove(file_name)
os.rename(file_name+'_new',file_name)



"""
import sys,os
src = sys.argv[1]
des = sys.argv[2]
file_name = sys.argv[3]

with open(file=file_name,mode='r') as f,         open(file=file_name+'_new',mode='w') as f_new:
    for i in f:
        if src in i:
            i = i.replace(src,des)
        f_new.write(i)

os.remove(file_name)
os.rename(file_name+'_new',file_name)
"""

相关推荐