使用argparse命令行读取csv文件时,需要注意一些细节。下面是一个示例代码:
import argparse
import csv
def read_csv_file(csv_file):
with open(csv_file) as f:
reader = csv.reader(f)
for row in reader:
print(row)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='CSV File Reader')
parser.add_argument('csv_file', help='Path to the CSV file')
args = parser.parse_args()
read_csv_file(args.csv_file)
在运行这个程序时,需要提供csv文件的路径作为命令行参数。例如:
$ python csv_reader.py data.csv
但是,当提供的路径不存在时,程序就会出现错误。为了避免这种情况,可以在程序中添加一些检查:
import os
def read_csv_file(csv_file):
if not os.path.exists(csv_file):
raise argparse.ArgumentTypeError(f"{csv_file} does not exist")
with open(csv_file) as f:
reader = csv.reader(f)
for row in reader:
print(row)
当传入的csv文件不存在时,就会抛出一个ArgumentTypeError异常,提示用户文件不存在。
除了文件是否存在的检查外,还需要注意传入的文件是否是csv格式的文件。可以在程序中添加另一个检查:
def read_csv_file(csv_file):
if not os.path.exists(csv_file):
raise argparse.ArgumentTypeError(f"{csv_file} does not exist")
_, ext = os.path.splitext(csv_file)
if ext.lower() != '.csv':
raise argparse.ArgumentTypeError(f"{csv_file} is not a CSV file")
with open(csv_file) as f:
reader = csv.reader(f)
for row in reader:
print(row)
这个函数会检查文件的后缀名是否为.csv,如果不是则抛出异常。这样就可以避免读取错误的文件类型了。