-1

Every time I try to change data to integers, I get this error

Error invalid literal for int() with base 10: '0,0,1 \n'

data = open("adj_matrix.txt", "r")
    
list_of_lists = []
for line in data.readlines():
    stripped_line = line.strip()
    line_list = stripped_line.split()
    list_of_lists.append(line_list)

data.close()

print(list_of_lists)

total = sum([int(num) for num in list_of_lists])
print(total)

Text file data:

0,0,1 
0,0,1 
1,1,0 
1,0,0
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • That's because every time `"0,0,1 \n"` does not represent *one* integer. – mkrieger1 Dec 01 '21 at 15:11
  • 1
    `split()` splits on whitespace. To split by `,`, use `split(',')` instead. I'm voting to close this as duplicate of ["pythonic" method to parse a string of comma-separated integers into a list of integers?](https://stackoverflow.com/questions/3477502/pythonic-method-to-parse-a-string-of-comma-separated-integers-into-a-list-of-i) – mkrieger1 Dec 01 '21 at 15:13

2 Answers2

0

Basically, it is caused because every line from the text file includes more than one integer.

As mkrieger said:

That's because every time "0,0,1 \n" does not represent one integer.

Notice: this format is known also as CSV (comma-separated values) so there are easier methods to deal with that files format.

Well, an optional solution is using spilt() method just separating the line by a separator (the default is whitespace, but it's changeable).

Pandas' approach

Pandas is a very useful library for data processing. Just for example, what you try to do could be implements in that compact way:

import pandas as pd
df = pd.read_csv('file.csv')
total = df.sum().sum()
print(total)
Yanirmr
  • 923
  • 8
  • 25
0

It looks like there are two issues, first with the string.strip(), and second with the string.split() method.

For string.strip(), its best if the characters are specified. In this case you'll want to strip '\n' and '\t' to ensure they aren't part the string anymore.

For string.split() its best to specify what character to split by such as ',' to split by comma. In this case splitting by comma will return a list of strings, with each string containing the value you want to turn into an int.

Messypuddle
  • 412
  • 6
  • 12