ShouldBeAProgramer
ShouldBeAProgramer

Reputation: 3

Convert a text file to a matrix

I've been trying to convert this time of data from a file into a matrix.

101 Bob 10
104 Lob 5
103 Dob 9
109 Dobby 4

The best thing I can do is transform it in a list such as this one.

['101 Bob 10', '104 Lob 5', '103 Dob 9', '109 Dobby 4']

The question is how can I transpose the file into a matrix?

Upvotes: 0

Views: 1321

Answers (2)

rpontual
rpontual

Reputation: 95

Perhaps you are looking for a solution such as this.

First open the file and read all lines ("with" will handle closing the file, the option 'r' ensures the file is opened for reading only).

with open('myfile.txt', 'r') as f:
    lines = f.readlines()    

At this stage all file content is in memory kept by the lines variable in a list, each item of the list is one line from the file.

Then take each line and split it using spaces as delimiter. The split function returns a list of strings, e.g. ['101', 'Bob', '10']. The split result needs to be placed in an outer list to emulate a matrix. These are two ways to do this:

output = []
for line in lines
    output.append(line.split(' ')

alternatively, you can use the condensed form to replace all three lines above.

output = [item.split(' ') for item in input]

Please note that as coded the entire file has to fit in memory, the line split only works if space can be used as delimiter.

print(output)
print(output[0][1])

The second print shows how a matrix can be emulated. The results are:

[['101', 'Bob', '10'], ['104', 'Lob', '5'], ['103', 'Dob', '9'], ['109', 'Dobby', '4']]
Bob

Upvotes: 1

jmd_dk
jmd_dk

Reputation: 13120

There is no such thing as a matrix among the native types of Python, hence the comments.

To read the file into a 2D NumPy array, try

import numpy as np
data = np.genfromtxt('filename', dtype=str)
print(data)
print(data.shape)
print(data[0, 1])

Note that all elements will be strs, so you will have to convert the numbers into proper ints afterwards (if needed).

Upvotes: 1

Related Questions