Python Forum

Full Version: Read strings and numbers in columns from a file
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi all,

I have a .txt file which has two columns. the first column is string and the second column is number. The structure of the .txt file is the following:

abcde  12345
aswd   65892
qwerty 45896
How can I create two lists where list1 is the first column and list2 is the second column?
Any help is much appreciated!
What have you tried?
So I tried using numpy but I realized that numpy can't handle strings so I was thinking of using something like this:
data = open('file.txt', 'r').read()
If could only had integers, I could use numpy like this:

data = np.loadtxt('file.txt')
lst1 = data[:, 0]
lst2 = data[:, 1]
But I don't know how I can implement both.

Can anyone please suggest me what I should do here?
np.loadtxt should be provided with dtypes (however, this is not providing 'two lists' as required):

import numpy as np
arr = np.loadtxt('data.txt', dtype={'names': ('string', 'integer'), 
                                    'formats': ('S6', 'i4')})

# array([(b'abcde', 12345), (b'aswd', 65892), (b'qwerty', 45896)],
#      dtype=[('string', 'S6'), ('integer', '<i4')])
To have two separate lists with plain Python one can just:

texts = []
nums = []

with open('data.txt', 'r') as f:
    for line in f:
        text, num = line.strip().split()
        texts.append(text)
        nums.append(int(num))

print(f'{texts=}')
print(f'{nums=}')

# texts=['abcde', 'aswd', 'qwerty']
# nums=[12345, 65892, 45896]
Thank you so so much!