python用来做文本文件的批量处理
python作为人人都会的编程语言,用来批量处理一些文本文件真的不要太舒服。这次来了一个需求,要把源文件org_file中的特定行lines_nums追加写入到另一个文件file。
简单用python实现了一下,主要思路就是遍历一下原来的文件,碰到要追加的行就追加一下。
def add_lines_to(org_file, lines_nums, file):
''' 根据行号lines_nums,将org_file的一部分追加到file
org_file: 原来的文件名
line_nums: 需要追加的行号,可以是多行,以一个列表或者range的形式
file: 需要写入的文件
'''
#如果指定的是某行
if isinstance(lines_nums, int):
index = 0
for line in open(org_file):
index += 1
if index == lines_nums:
with open(file, 'a') as f:
f.writelines(line)
break
else:
if isinstance(lines_nums, list):
lines_nums.sort()
index = 0
jndex = 0
for line in open(org_file):
index += 1
if index == lines_nums[jndex]:
jndex += 1
with open(file, 'a') as f:
f.writelines(line)
if jndex == len(lines_nums):
break
if __name__ == '__main__':
import sys
orf = sys.argv[1]
f = sys.argv[2]
l_nums = []
for i in range(3, len(sys.argv)):
l_nums.append(int(sys.argv[i]))
print("I will add line " + sys.argv[i] + " in file " + orf + " to file " + f)
add_lines_to(orf, l_nums, f)
后记
当然,这个操作也就是windows用户可能会用到了,毕竟在linux/mac下我们只需要一个sed -n '2,7p' $org_file >> $file
就完事儿了。