Reputation: 13
I was trying to read a .txt file and append it into a list inside a list, but I had encounter this problem.
ValueError: invalid literal for int() with base 10: '-'
In which my code are like this:
def readfiles(filename):
with open(filename) as f:
content = f.readlines()
matrix=[]
tem=[]
for i in range(len(content)):
tem=[]
content[i] = content[i].replace('\n','')
content[i] = content[i].replace(',', '')
for j in range(len(content[i])):
tem.append(int(content[i][j]))
matrix.append(tem)
return matrix
but if i replace the tem.append(int(content[i][j])) to tem.append(content[i][j])
the list appear to be different which somehow look like this:
[['3', '-', '2', '1'], ['4', '-', '1', '0'], ['0', '2', '1']]
I wanted my function to read negative value from a file. Can anyone help with this ?
my .txt file look like this:
3,-2,1
4,-1,0
0,2,1
Upvotes: 1
Views: 4326
Reputation: 27323
I'm guessing that this would work:
def readfiles(filename):
with open(filename) as f:
return [[int(num) for num in line.split(",")] for line in f]
The problem you're having is that you're iterating over your line (which is a string), which gets you individual characters rather than "things between commas":
Let's say the current line (content[i]
) is "3,-2,1"
.
After this:
content[i] = content[i].replace(',', '')
content[i]
is now "3-21"
. How is it supposed to know what your numbers are? Iterating over that string gives you "3", "-", "2", "1"
, where "-"
causes the exception to be thrown.
Upvotes: 1
Reputation: 2604
If you have for example a string like this:
numbers = "-6, 3, -3, 18"
You always can do this:
print [int(n) for n in numbers.split(',')]
To get:
[-6, 3, -3, 18]
Maybe you need change the way to process your file, please add a extrat to show us how the numbers are in it.
Upvotes: 1