简体   繁体   English

如何读取命令行参数传递的txt

[英]how to read a txt passed by command line argument

i want to pass a txt file by command line argument using the argparse module and read the file with open() function but first thing i've encountred was this error : 我想使用argparse模块通过命令行参数传递txt文件,并使用open()函数读取文件,但是我遇到的第一件事是此错误:

AttributeError: 'dict' object has no attribute 's'

Here is my code 这是我的代码

import argparse
parser = argparse.ArgumentParser(description="My program!", formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument("-s", type=argparse.FileType('r'), help="Filename/path to be passed")
args = vars(parser.parse_args())
subfile = (open(args.s, "r")).read()

you can directly read from args['s'] , since type=argparse.FileType('r') . 您可以直接从args['s']读取,因为type=argparse.FileType('r') No open() needed: 不需要open()

import argparse
parser = argparse.ArgumentParser(description="My program!", formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument("-s", type=argparse.FileType('r'), help="Filename/path to be passed")
args = vars(parser.parse_args())
data = args['s'].readlines()
print(data)

now you can call the script from the command prompt, eg as python .\\test.py -s'D:/test.txt' with test.txt containing two lines with letters 'abc': 现在您可以从命令提示符处调用脚本,例如python .\\test.py -s'D:/test.txt'其中test.txt包含两行带有字母'abc'的行:

# prints ['abc\n', 'abc\n']

edit - you can simplify the code to 编辑-您可以简化代码以

parser = argparse.ArgumentParser(description="My program!", formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument("-f", type=argparse.FileType('r', encoding='UTF-8'), help="path/filename of file to be passed")
data = parser.parse_args().f.readlines()

changes: 变化:

  • changed the parameter name to f which I find better-suited for a filename input 将参数名称更改为f ,我觉得它更适合文件名输入
  • added and encoding to type=argparse.FileType('r') - otherwise, it will take the OS default (eg on Windows: cp1252). 添加并编码为type=argparse.FileType('r') -否则,它将采用操作系统默认值(例如,在Windows上为cp1252)。 I'd consider it better practice to explicitly specify the encoding. 我认为最好明确指定编码。
  • directly accessed the io.TextIOWrapper with parser.parse_args().f instead of creating a dict object first with vars() 直接使用parser.parse_args().f访问io.TextIOWrapper ,而不是先使用vars()创建dict对象

Replace the last line: 替换最后一行:

subfile = (open(args.s, "r")).read()

with: 与:

with open( args['s'] ) as fin :
    subfile = fin.read()

Things magically start to work and you don't have an open file hanging around for no particular reason. 事情开始神奇地起作用,并且没有特殊原因,您没有打开的文件在附近徘徊。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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