Search code examples
pythonloopsisnumericisalpha

Reading and extracting useful data from a file with a loop fails to produce a list of values


I am reading a file with some data. I wish to divide the data into several categories and write these into files of their own (for example integers, like phone numbers; decimals; single words; and separate sentences).

def data_reading():
    data = []
    integers = []
    with open("my_lines.txt") as file:
        for row in file:
            row = row.strip().replace("\n", "")
            data.extend(row.split(","))
        for values in data:
            if values.isnumeric():
                print(values + " - integer")
                integers.extend(row.split(","))
            elif values.isalpha():
                print(values + " - alphabetical strings")
            elif values.isalnum():
                print(values + " - alphanumeric")
            else:
                print(values + " - float")          
    return integers

somethin = data_reading()
print(somethin)

If I am to input lines like 123, abc, Address unknown, 20.12.85, I was aiming to get 4 lists to store values and use these to write in the 4 files with separate write functions. However, now I am only storing the last float value as many times as I have lines in the data file I am reading (I was trying to get the numbers with isnumerical()). How come? I seem to be missing something.


Solution

  • You have two seperate for loops, when you put your integer into the list you already iterated over all the lines in the file, so row points to the last row, which is "20.12.85".

    Use integers.append(values) instead (or integers.append(int(values)) if you want to store an actual integer).

    Like this:

    def data_reading():
        data = []
        integers = []
        with open("my_lines.txt") as file:
            for row in file:
                row = row.strip().replace("\n", "")
                data.extend(row.split(","))
            for value in data:
                if value.isnumeric():
                    print(value + " - integer")
                    integers.append(value)
                elif value.isalpha():
                    print(value + " - alphabetical strings")
                elif value.isalnum():
                    print(value + " - alphanumeric")
                else:
                    print(value + " - float")
        return integers
    
    somethin = data_reading()
    print(somethin)