Python Forum
Read strings and numbers in columns from a file - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Read strings and numbers in columns from a file (/thread-28960.html)



Read strings and numbers in columns from a file - suvadip - Aug-11-2020

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!


RE: Read strings and numbers in columns from a file - ndc85430 - Aug-11-2020

What have you tried?


RE: Read strings and numbers in columns from a file - suvadip - Aug-11-2020

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?


RE: Read strings and numbers in columns from a file - perfringo - Aug-11-2020

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]



RE: Read strings and numbers in columns from a file - suvadip - Aug-11-2020

Thank you so so much!