简体   繁体   中英

Read a file via argparse and print the file contents line by line

I want to

Code:

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.")

I cannot get the file lines to print out and the exception to run if the file is incorrect.

Why are you opening in binary mode? Also, your try/catch is in the wrong place

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM