Daniel Andersson
Daniel Andersson

Reputation: 199

Python fill matrix with content from file (integers)

I have a program that opens and reads a text file.

The text file will always be in the following format with 3 columns and a unspecified amount of rows:

1234,0,5

1235,5,10

1236,10,15

…………

………….

I have successfully initialized a matrix with its size depending on the amount of lines in the file.

But how can I now fill the matrix with each integer in the correct column and row?

def main():
    f = open(text.txt, "r")
    f1 = f.readlines()

    # matrix 
    w = 3
    Matrix = [[0 for x in range(w)] for y in f1]

enter image description here

Upvotes: 0

Views: 220

Answers (1)

onepan
onepan

Reputation: 954

You've almost got it, you just need to use the data you have in your f1 variable.

def main():
    with open("text.txt", "r") as f:
        f1 = f.readlines()

    # matrix 
    Matrix = [[int(x) for x in y.split(",")] for y in f1]

That said, if you're okay with using other libraries many can do the work for you.

e.g.: numpy:

import numpy as np

matrix = np.loadtxt("test.txt", dtype="int", delimiter=",")

pandas:

import pandas as pd

matrix = pd.read_csv("test.txt")

Upvotes: 1

Related Questions