Python 如何使用argparse打开文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18862836/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 12:05:03  来源:igfitidea点击:

How to open file using argparse?

pythonargparse

提问by nuT707

I want to open file for reading using argparse. In cmd it must look like: my_program.py /filepath

我想使用 argparse 打开文件进行读取。在 cmd 中它必须看起来像:my_program.py /filepath

That's my try:

这是我的尝试:

parser = argparse.ArgumentParser()
parser.add_argument('file', type = file)
args = parser.parse_args()

采纳答案by wim

The type of the argument should be string (which is default anyway). So make it like this:

参数的类型应该是字符串(无论如何都是默认的)。所以让它像这样:

parser = argparse.ArgumentParser()
parser.add_argument('filename')
args = parser.parse_args()
with open(args.filename) as file:
  # do stuff here

回答by ilent2

Take a look at the documentation: http://docs.python.org/2/library/argparse.html#type

看一下文档:http: //docs.python.org/2/library/argparse.html#type

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('file', type=argparse.FileType('r'))
args = parser.parse_args()

print args.file.readlines()

回答by yPhil

This implementation allows the "file name" parameter to be optional, as well as giving a short description if and when the user enters the -hor --helpargument.

此实现允许“文件名”参数是可选的,并在用户输入-hor--help参数时提供简短描述。

parser = argparse.ArgumentParser(description='Foo is a program that does things')
parser.add_argument('filename', nargs='?')
args = parser.parse_args()

if args.filename is not None:
    print('The file name is {}'.format(args.filename))
else:
    print('Oh well ; No args, no problems')

回答by Ming

In order to have the file closed gracefully, you can combine argparse.FileType with the "with" statement

为了优雅地关闭文件,您可以将 argparse.FileType 与“with”语句结合使用

# ....

parser.add_argument('file', type=argparse.FileType('r'))
args = parser.parse_args()

with args.file as file:
    print file.read()

--- update ---

- - 更新 - -

Oh, @Wernight already said that in comments

哦,@Wernight 已经在评论中说过了

回答by Thomas Ahle

I'll just add the option to use pathlib:

我将添加使用选项pathlib

import argparse, pathlib

parser = argparse.ArgumentParser()
parser.add_argument('file', type=pathlib.Path)
args = parser.parse_args()

with args.file.open('r') as file:
    print(file.read())