- 论坛徽章:
- 4
|
在shell下运行:
python replace_line.py --input your_input_file -a a -b b --output your_out_file
a 和 b 表示要替换的两行- #!/usr/bin/env python
- # -*- coding: utf-8 -*-
- __author__ = 'shengwei ma'
- '''http://bbs.chinaunix.net/thread-4243850-1-1.html'''
- import sys
- import getopt
- input_file = ""
- output_file = ""
- a = ""
- b = ""
- try:
- opts, args = getopt.getopt(sys.argv[1:], "ha:b:", ["input=", "output="])
- except getopt.GetoptError as err:
- print(str(err))
- for op, value in opts:
- if op == "--input":
- input_file = value
- elif op == "-a":
- a = int(value)
- elif op == "-b":
- b = int(value)
- elif op == "--output":
- output_file = value
- elif op == "-h":
- print("python replace_line.py --input your_input_file -a a -b b --output your_out_file")
- sys.exit()
- # 以上代码可以忽略,定义输入输出文件,以及a b参数
- alist = []
- with open(input_file, 'r') as f: # 打开输入文件
- for line in f.readlines():
- line = line.strip()
- alist.append(line) # 读入所有行,放入列表alist, 注意 alist[0]代表第一行, alist[1] 表示第二行,所以下述 是 a-1 b -1
- pattern = {alist[a - 1]: alist[b - 1], alist[b - 1]: alist[a - 1]} # a b 互换
- new_list = [pattern[x] if x in pattern else x for x in alist] # 执行
- with open(output_file, 'w') as output: # 打开 输出文件
- for new in new_list:
- output.write(new + '\n') # 按行写入
复制代码 |
|