通过argparse读取文件并逐行打印文件内容

时间:2018-04-04 20:55:12

标签: python json list

我想

代码:

import argparse

import csv

import os

parser = argparse.ArgumentParser(description = "Parse the json file")

parser.add_argument("-f", help="file to upload")

args = parser.parse_args()

fileName = args.f

with open(filename, 'rb') as f:

    try:
        for lines in f:
        print(lines)


    except:
        print("The file " + fileName + " could not be opened.")

我无法打印出文件行,如果文件不正确则运行异常。

1 个答案:

答案 0 :(得分:0)

为什么要以二进制模式打开?此外,您的try / catch位于错误的位置

try:
    with open(filename) as f:
        for line in f:
            print(line)
except:
    print('The file ' + filename + ' could not be opened.')
相关问题