Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read a text file into separate lists python

Tags:

python

file-io

Say I have a text file formatted like this:

100 20 the birds are flying

and I wanted to read the int(s) into their own lists and the string into its own list...how would I go about this in python. I tried

data.append(map(int, line.split()))

that didn't work...any help?

like image 677
quantumdisaster Avatar asked Dec 30 '25 16:12

quantumdisaster


1 Answers

Essentially, I'm reading the file line by line, and splitting them. I first check to see if I can turn them into an integer, and if I fail, treat them as strings.

def separate(filename):
    all_integers = []
    all_strings = []
    with open(filename) as myfile:
        for line in myfile:
            for item in line.split(' '):
                try:
                    # Try converting the item to an integer
                    value = int(item, 10)
                    all_integers.append(value)
                except ValueError:
                    # if it fails, it's a string.
                    all_strings.append(item)
    return all_integers, all_strings

Then, given the file ('mytext.txt')

100 20 the birds are flying
200 3 banana
hello 4

...doing the following on the command line returns...

>>> myints, mystrings = separate(r'myfile.txt')
>>> print myints
[100, 20, 200, 3, 4]
>>> print mystrings
['the', 'birds', 'are', 'flying', 'banana', 'hello']
like image 88
Michael0x2a Avatar answered Jan 02 '26 04:01

Michael0x2a