ValueError while trying to split line extracted from file
Question:
with open(st) as file:
for line in file:
line = line.rstrip()
name, species, homeworld = line.split("t")
characters.append(StarWarsCharacter(name, species, homeworld))
I’m trying to extract data, but I just get a value error:
ValueError:
name, species, homeworld = line.split("t")
ValueError: not enough values to unpack (expected 3, got 1)
Answers:
First of all, the name of the file should be a string, the it should be "st"
. Second, the error is clear: it means that the split returns only one token, but you expected 3. Then, the file you are trying to read is not separated by "t"
. In fact, trying to reproduce:
script.py:
with open("st") as file:
for line in file:
line = line.rstrip()
ame, species, homeworld = line.split("t")
Note that i didnt include the last line because I don’t have these structs.
st:
pluto dog homeworld
Running the command python script.py
i don’t have any error, because my file is correctly separated by "t"
.
You are expecting that each line can be split into 3 parts based on the separator t
.
But if it is not true you will get this error.
Additionally as commented by CrazyChucky, this can also happen if the line is empty.
Consider this example:
line = "a; b; c"
p1, p2, p3 = line.split(';')
p1, p2, p3 = line.split(',') # ValueError: not enough values to unpack (expected 3, got 1)
The line cannot be split into three part based on the separator ,
.
with open(st) as file:
for line in file:
line = line.rstrip()
name, species, homeworld = line.split("t")
characters.append(StarWarsCharacter(name, species, homeworld))
I’m trying to extract data, but I just get a value error:
ValueError:
name, species, homeworld = line.split("t")
ValueError: not enough values to unpack (expected 3, got 1)
First of all, the name of the file should be a string, the it should be "st"
. Second, the error is clear: it means that the split returns only one token, but you expected 3. Then, the file you are trying to read is not separated by "t"
. In fact, trying to reproduce:
script.py:
with open("st") as file:
for line in file:
line = line.rstrip()
ame, species, homeworld = line.split("t")
Note that i didnt include the last line because I don’t have these structs.
st:
pluto dog homeworld
Running the command python script.py
i don’t have any error, because my file is correctly separated by "t"
.
You are expecting that each line can be split into 3 parts based on the separator t
.
But if it is not true you will get this error.
Additionally as commented by CrazyChucky, this can also happen if the line is empty.
Consider this example:
line = "a; b; c"
p1, p2, p3 = line.split(';')
p1, p2, p3 = line.split(',') # ValueError: not enough values to unpack (expected 3, got 1)
The line cannot be split into three part based on the separator ,
.