Noodles
Noodles

Reputation: 3

Inputting a file of mixed data types and converting numbers into ints using Python

I have a project I am working on for school which requires me to input a given file of data and do several manipulations with the data in the file. The problem I am having is the data is both string type and number. I need the numbers to be in int format so I can use them mathematically later on, but the string is important to their relevance here is an example of input text I would use:

example1  10 20 30
example2  40 50 60
example3  70 80 90

I like it to input into a variable as array's within an array using a simple code like this:

def inputData():
    bank = []
    with open("example.txt", "r") as file:
        for line in file:   
             bank.append(line.split())
    return bank

This would return results like:

[['example1','10','20','30'],['example2','40','50','60'],['example3','70','80','90']]

I like this returning as arrays within arrays, but when I convert it, it removes the individual arrays and returns it as one long list. Here is my code with it converting:

def readData():
    bank= []
    with open("example.txt", "r") as file:
        for line in file:   
            line = line.split()
            for i in line:
                if i.isdigit() is True:
                    bank.append(int(i))
                else:
                    bank.append(i)
    return bank

Is it possible to convert the input and keep it in individual arrays?

Thanks in advance for any help

Upvotes: 0

Views: 74

Answers (1)

Delgan
Delgan

Reputation: 19627

You have to initate a new empty list from within the loop, append split and casted elements to it and finally add this list to the final bank.

The method .split() is returning a list, this is why you get the expected result when you did bank.append(line.split()).

def readData():
    bank= []
    with open("example.txt", "r") as file:
        for line in file:   
            line = line.split()
            sub_bank = []
            for i in line:
                if i.isdigit() is True:
                    sub_bank.append(int(i))
                else:
                    sub_bank.append(i)
            bank.append(sub_bank)
    return bank

Moreover, i.isdigit() returns a boolean so you do not have to write is True.

Finally, you should take a look at list comprehension which may make your code more readable:

def readData():
    bank = []
    with open("example.txt", "r") as file:
        for line in file:
            bank += [int(i) if i.isdigit() else i for i in line.split()]
    return bank

Upvotes: 1

Related Questions