如何使用 arg 解析器库打印参数传递文件的前 n 行
How to print first n line from the argument passed file with arg parser library
如何使用 arg 解析器库从作为文件传递的参数打印 N 行。
我有一个 100 行的文件。我想打印前 n 行。我还需要使用 argparser,因为我不想在 python 脚本
中编辑文件
在下面的脚本中,N 是要打印的前 N 行。还需要将其作为参数
import argparse
parser = argparse.ArgumentParser(description='print n lines')
parser.add_argument('filename',type=argparse.FileType('r'), help='Path to file name')
args = parser.parse_args()
with open("filename") as myfile:
head = [next(filename) for x in range(N)]
print (head)
我的用法
python file.py file.txt -c 10
它将打印文件的前 10 行。
我认为您应该添加另一个 argparse 参数。
类似于:
import argparse
parser = argparse.ArgumentParser(description='print n lines')
parser.add_argument('filename',type=argparse.FileType('r'), help='Path to file name')
parser.add_argument('--n_lines',type='int', help='Number of line to print')
args = parser.parse_args()
with open(args.filename) as myfile:
head = [next(myfile) for x in range(args.n_lines)]
print (head)
通过执行此操作循环遍历文件中的行
with open("file.txt") as myfile:
lines = myfile.readlines()
for line in lines[0:10]:
print(line)
这将打印前 10 行,即第 0 行到第 10 行。
如何使用 arg 解析器库从作为文件传递的参数打印 N 行。
我有一个 100 行的文件。我想打印前 n 行。我还需要使用 argparser,因为我不想在 python 脚本
中编辑文件在下面的脚本中,N 是要打印的前 N 行。还需要将其作为参数
import argparse
parser = argparse.ArgumentParser(description='print n lines')
parser.add_argument('filename',type=argparse.FileType('r'), help='Path to file name')
args = parser.parse_args()
with open("filename") as myfile:
head = [next(filename) for x in range(N)]
print (head)
我的用法
python file.py file.txt -c 10
它将打印文件的前 10 行。
我认为您应该添加另一个 argparse 参数。 类似于:
import argparse
parser = argparse.ArgumentParser(description='print n lines')
parser.add_argument('filename',type=argparse.FileType('r'), help='Path to file name')
parser.add_argument('--n_lines',type='int', help='Number of line to print')
args = parser.parse_args()
with open(args.filename) as myfile:
head = [next(myfile) for x in range(args.n_lines)]
print (head)
通过执行此操作循环遍历文件中的行
with open("file.txt") as myfile:
lines = myfile.readlines()
for line in lines[0:10]:
print(line)
这将打印前 10 行,即第 0 行到第 10 行。