pythonの使用例

 replace.py

#!/usr/bin/env python
# --*-- encoding=UTF-8 --*--
#author: wh fang
#date:2018-05-10

import os
import sys
import shutil

if __name__=="__main__":
    print (sys.argv)
    print (len(sys.argv))
    if (len(sys.argv) < 4):
        print ("you must input 4 arguments")
    scatter_file = sys.argv[1]
    key_word = sys.argv[2]
    update_file =  sys.argv[3]
    tmp_file = sys.argv[4]
    scatter_path= os.path.dirname(scatter_file)
    update_file_name = os.path.basename(update_file)
    replace_file_name  = None
    print (scatter_path)
    print (update_file_name)
    print (os.path.basename(scatter_file))
    # f_scatter = open(scatter_file,'r+')
    # print (f_scatter.readlines())
    with open(scatter_file, "r+") as f_scatter:
        for line in f_scatter:
            if (line.find(key_word,0, len(line)) > 0):
                line = line.strip()
                list = line.split(" ")
                print (list)
                for i in range(list.count('')):
                   list.remove('')
                print (list)
                replace_file_name = list[len(list) -1]
                line_new = line.replace(replace_file_name, update_file_name)
                print (line_new)

    with open(scatter_file, "r+") as f_scatter:
        print ("read again")
        f_content = f_scatter.read()
        f_content_new = f_content.replace(replace_file_name,update_file_name)
        print (f_content_new)
        f_scatter.seek(0)
        f_scatter.write(f_content_new)

    shutil.copy(update_file,scatter_path)
#    os.remove(scatter_path+"/"+replace_file_name)
    with open(tmp_file,"r+") as f:
        f.writelines(scatter_path+"/"+replace_file_name+"\n")
        f.writelines(scatter_path+"/"+os.path.basename(update_file))

 

 

 

公開された17元の記事 ウォンの賞賛2 ビュー20000 +

おすすめ

転載: blog.csdn.net/toove/article/details/100990597
おすすめ