python - 如何在python中以N为参数打印文件的前N行
问题描述
我将如何在 python 中获取文本文件的前 N 行?N 必须作为论据
用法:
python file.py datafile -N 10
我的代码
import sys
from itertools import islice
args = sys.argv
print (args)
if args[1] == '-h':
print ("-N for printing the number of lines: python file.py datafile -N 10")
if args[-2] == '-N':
datafile = args[1]
number = int(args[-1])
with open(datafile) as myfile:
head = list(islice(myfile, number))
head = [item.strip() for item in head]
print (head)
print ('\n'.join(head))
我写了程序,可以让我比这段代码更了解
解决方案
假设您实现的 print_head 逻辑不需要更改,这是我认为您正在寻找的脚本:
import sys
from itertools import islice
def print_head(file, n):
if not file or not n:
return
with open(file) as myfile:
head = [item.strip() for item in islice(myfile, n)]
print(head)
def parse_args():
result = {'script': sys.argv[0]}
args = iter(sys.argv)
for arg in args:
if arg == '-F':
result['filename'] = next(args)
if arg == '-N':
result['num_lines'] = int(next(args))
return result
if __name__ == '__main__':
script_args = parse_args()
print_head(script_args.get('filename', ''), script_args.get('num_lines', 0))
运行脚本
python file.py -F datafile -N 10
注意:实现它的最佳方法是使用argparse
库
推荐阅读
- amazon-web-services - 如何设置 RStudio 服务器以在 AWS 上使用 SSL 运行?
- sorting - 按字母顺序排序表
- terraform - Terraform - 在多个帐户中部署
- android - 如何为 Google PlaceAutocomplete 设置语言
- django - 如何使用 request.FILES(django 1.11) 将 csv 文件数据加载到 pandas 中而不在服务器上保存文件
- batch-file - 如何在for循环中批量使用多个find命令?
- android - MPAndroidChart - getChartBitmap 不显示折线图
- javascript - 从 WP API 传递一个值做 Vue href?
- c - 指向结构的指针声明会为其成员分配内存吗?
- sas - proc 报告 sas 中的自定义摘要