简体   繁体   中英

Python: Read file with negative number

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM