简体   繁体   中英

Reading integers from a file in python

I'm reading from a file that contains 100000 numbers (1 per line) using:

var_array = []

with open("IntegerArray.txt", "r") as my_file:
    for line in my_file:
        var_array += line.strip().split('\n')

print(var_array)

This returns an array of strings, but I need to convert them into integers. I tried to use:

var_array += int(line.strip().split('\n'))

But it throws the error "TypeError: int() argument must be a string or a number, not 'list'".

I also tried to use map:

var_array.append(map(int,line.strip().split('\n')))

But the printing shows this (88>, , , ...)

Thanks for any advise.

The problem is in split('\\n') function call that converts line into a list of tokens separated by \\n character (which should not exist in the line since you are doing strip() ). Remove this call and wrap line.strip() call with int() and everything should be OK.

Here is updated version:

var_array = []

with open("IntegerArray.txt", "r") as my_file:
    for line in my_file:
        var_array.append(int(line.strip()))

print(var_array)

you dont need split here:

var_array.append(int(line.strip()))

strip and split:

>>> "hello,world".split(',')    #split the string on delimiter 
['hello', 'world']
>>> "   hello,world  \r\n".strip()  #removes whitespace from the both end
'hello,world'

If you have Pandas installed then it easier to work with:

>>> import pandas as pd
>>> pd.read_csv('IntegerArray.txt', header=None)
   0
0  1
1  3
2  4
3  5

If you want it as builtin datatypes:

>>> list(pd.read_csv('IntegerArray.txt', header=None).values[:,0])
[1, 3, 4, 5]

You need to split on the delimiter not the newline:

var_array += map(int, line.strip().split())

If they are separated by empty spaces just split, if each number is separated by a , use split(",") etc..

If they are all on individual lines just use a list comp and cast as int:

with open("IntegerArray.txt") as my_file:
        var_array = [int(line.rstrip()) for line in my_file]

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