这里写个简单的,用readline即可实现,命令行带入参数1为读取的文件名,参数2为需要读取的行数。需要读取多行,你可以简单改改,例如参数带个列表,程序内用eval转化为数组之类的方法。
import sys
filename = sys.argv[1]
linenum = int(sys.argv[2])
with open(filename , 'r') as f:
line = f.readline()
n = 1
while line:
if linenum == n:
print line
break
else:
line = f.readline()
n += 1
# readsomelines.py
# !/usr/bin/env python3
import sys
fname = 'aa.txt'
def main():
lines = [i for i in sys.argv[1:] if i.isdigit()]
with open(fname) as f:
s = f.read().split('\n')
print('file name: {}, total: {} lines.'.format(fname, len(s)))
for i in lines:
index = int(i) - 1
content = s[index] if index < len(s) else ''
print('line {}: {}'.format(i, content))
main()
$ python readsomelines.py 2 3
file name: aa.txt, total: 5 lines.
line 2: (comment line)
line 3: (atom symbol) 1 1 1