我试图将文件的第一行拆分为 3 个单独的值,但它给了我一个错误
ValueError: not enough values to unpack (expected 3, got 1)
#open files
infile = open("milkin.txt","r").readlines()
outfile = open("milkout.txt","w")
#instantiate variables
a,b,c = infile[0].split()
牛奶.txt
abc
def
ghi
请您参考如下方法:
首先,split()如果未指定参数,则默认使用空格。
>>> 'abc'.split()
['abc']
幸运的是,要将字符串解压缩为多个值,您不需要 split()字符串。由于字符串本身是可迭代的,因此只要确保字符串的长度与声明变量的数量匹配,就可以解压多个值。
>>> a, b, c = 'abc'
>>> a
'a'
>>> b
'b'
>>> c
'c'
另外,readlines()文件对象的方法返回包含尾随换行符的字符串列表,因此您可能认为只是字符串 'abc'在 infile[0]真的是'abc\n' .
这应该有效:
a, b, c = infile[0].strip()
