与输入文件相关的错误,ValueError:需要超过1个值才能取消

2024-05-29 03:34:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图从我拥有的一本编码手册中运行以下代码,但出现以下错误:

回溯(最近一次呼叫): 文件“ex20.py”,第3行,in 脚本,输入文件=argv ValueError:需要多个值才能解包

我已经创建了一个名为input\ u file的txt文件,并尝试了其他故障排除方法,但仍然会出现错误。你知道吗

from sys import argv

script, input_file = argv

def print_all(f):
        print f.read()

def rewind(f):
    f.seek(0)

def print_a_line(line_count, f):
    print line_count, f.readline()

current_line = open(input_file)

print "First let's print the whole file:\n"

print_all(current_file)

print("Now lets rewind, kind of like a tape")

current_line = 1
print_a_line(current_line, current_line)

current_line = current_line + 1
print_a_line(current_line, current_file)

我希望它能按代码打印和工作。你知道吗


Tags: 文件代码编码inputdefcount错误line
3条回答

当您有“超过1个要解包的值”时,问题就会出现,这并不奇怪,这意味着argv小于您要分配给的变量数。你知道吗

如果希望代码行正常工作,或者只通过argv访问argv值而不进行赋值,则应确保argv长度正好为2,但是,如果您确实希望保持原样,我建议在之前进行快速测试:

if len(argv) != 2:
    exit()

以及之后的代码。但是您需要记住使用适当数量的arg运行代码,如下所示:

python <your_script_file>.py arg1

以这种方式,将arg1替换为要分配给input_file的值,因为argv[0]始终是正在运行的脚本/文件的名称。你知道吗

我想你应该用argumentParser之类的库。你知道吗

这个错误意味着argv没有“足够的值来解包”,也就是说,您试图通过执行称为destructuring的操作从argv变量分配scriptinput_file,但是argv只有一个值(脚本的名称)

似乎您运行脚本时没有提供参数(输入文件)。 应按以下方式运行脚本:

python ex20.py 'path/to/input_file'
script, input_file = argv

根据[Python 3.Docs]: sys.argv

The list of command line arguments passed to a Python script.

因此,无论参数是否传递给脚本(或者脚本是否传递给解释器),它始终是一个列表(序列)。你知道吗

因为在左侧有两个变量(scriptinput\u file),列表还应该包含两个元素(根据错误文本,您只包含一个-这意味着没有给脚本提供任何参数)。你知道吗

在幕后,[Python 3.Docs]: More Control Flow Tools - Unpacking Argument Lists发生了。你知道吗

处理这种情况的一种常见方法是检查列表中有多少元素:

if len(argv) != 2:
    raise SystemExit("Script should receive exactly one argument!")

当从cmdline调用解释器(脚本)时,请确保还为输入文件传递一个值。你知道吗

@EDIT0

从技术上讲,这超出了(原始)问题的范围。你知道吗

代码包含一堆无意义的部分(主要是因为混淆了当前的\u文件当前的\u行——这表示命名错误)。我不打算坚持使用它们,而是按原样粘贴代码:

import sys


def print_all(f):
    print(f.read())


def rewind(f):
    f.seek(0)


def print_a_line(line_number, f):
    print(line_number, f.readline())


_, input_file_name = sys.argv

input_file = open(input_file_name)

print("First, let's print the whole file:\n")
print_all(input_file)
print("Now lets rewind, kind of like a tape:\n")
rewind(input_file)
current_line = 1
print_a_line(current_line, input_file)
current_line += 1
print_a_line(current_line, input_file)

请注意,尽管您提到了使用Python 2prints也将在Python 3中工作。你知道吗

相关问题 更多 >

    热门问题