create a matrix from a file of strings in python

To create a matrix from a file of strings in Python, you can use the following steps:

  1. Read the file line by line and store each line as a string in a list.
  2. Split each string in the list using a separator (such as comma) to get a list of individual elements.
  3. Create a 2D list (matrix) by appending these lists as rows.
  4. Convert the strings into the appropriate data types as needed.

Here's the code:

main.py
# Open the file for reading
with open("filename.txt", "r") as file:
    # Read the lines and store them as a list of strings
    lines = file.readlines()

# Create an empty list to store the matrix
matrix = []

# Iterate over each string in the list of lines
for line in lines:
    # Remove the newline character at the end
    line = line.strip()
    # Split the line into individual elements using comma as the separator
    elements = line.split(",")
    # Convert the elements to the appropriate data types as needed
    # Add the list of elements as a row in the matrix
    matrix.append([int(e) for e in elements])

# Print the matrix
print(matrix)
655 chars
21 lines

Note: This code assumes that the file contains comma-separated integers. You may need to modify it accordingly if your file contains different types of data or has a different separator.

gistlibby LogSnag