Python3 eval function cause 'SyntaxError: unexpected EOF while parsing'

created at 02-10-2022 views: 6

problem

Using python3 to practice, when using the eval statement to convert text data into a list, an error SyntaxError: unexpected EOF while parsing is reported. The specific code is as follows

wrong code

datals= [ ]
f= open("data.txt",encoding='utf-8')
for line in f :
    line = line.replace("\n","")
    datals.append(list(map(eval,line.split(","))))
f.close()

solution

add if determination if value is empty

datals= [ ]
f= open("data.txt",encoding='utf-8')
for line in f :
    line = line.replace("\n","")
    if line!="":    # If the parameter in eval is empty, an error occurs, and if judgment needs to be added
        datals.append(list(map(eval,line.split(","))))
f.close()

There is no error when reading the data after running

data.txt is as follows

result

created at:02-10-2022
edited at: 02-10-2022: