求助,当我使用open()函数读取文件时,最终报错 Cannot open console output buffer for reading

我在使用open()函数读取文件时,最终报错
Cannot open console output buffer for reading

在使用该函数时,我引入了argparse并以短参数-r指定了文件路径,部分代码如下

run = argparse.ArgumentParser()
run.add_argument('-r',dest='read',help='获取文件路径')
run.add_argument('-p','--port',help='用逗号隔开')
args = run.parse_args()
if  args.read and args.port:
    port = args.port
    dir = args.read
    for a in  open(dir):
        for i in port:
            print(a,i)

求助

讨论数量: 2
Jason990420

It is caused by the argument of the built-in function open, open(dir) called here.

>>> open(True)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Cannot open console output buffer for reading
>>> open(2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Cannot open console output buffer for reading

Basically, wrong file path dir to open in your code, check how you use your script ?

d:\>python example.py -r d:\example.txt -p abc
'Line1\n' a
'Line1\n' b
'Line1\n' c
'Line2\n' a
'Line2\n' b
'Line2\n' c
'Line3' a
'Line3' b
'Line3' c
1个月前 评论
fishhero (楼主) 1个月前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!