Search code examples
pythonionested-loopsnested-listsfile-writing

Writing nested lists into file and reading back again in python


I'm practicing how to be more fluent with the combination of nested loops, nested lists, and IO in python.

For the sake of practice, I'm trying to write a nested list onto a file, and then use IO to read the content of the file back to the screen again - but unfortunately, I ran into trouble.

Can anybody help me out?

My (sort of stupid) code:

row1 = [1, 2, 3]
row2 = [4, 5, 6]
row3 = [7, 8, 9]

matrix = [row1, row2, row3]


def write_data_matrix(filename, in_list):
    outfile = open(filename, "w")

    for listitem in in_list:
        outfile.write(f"{listitem},\n")       #Works
                                          
    outfile.close()

write_data_matrix("matrix.txt", matrix)


def read_file(filename):                              #Does not work as intended
    infile = open(filename, "r")

    for line in infile:
        linje = line.strip("[").strip("]").split(",")
        print(linje)

    infile.close()

read_file("matrix.txt")

My first question is:

  1. Ideally I would like to make the write_data_matrix() function to write the content onto the file like shown below. Can anyone help me out?
1 2 3
4 5 6
7 8 9

The second question I have is:

  1. How do you read nested lists from a file that looks like this:
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],

and print it out to the console like this?

1, 2, 3
4, 5, 6
7, 8, 9 

All help is welcomed and strongly appreciated

Best regards a noob who tries to be better at coding :-)


Solution

  • Use This, the '\n'(newline) needs to be handled

    def read_file(filename):
        infile = open(filename, "r")
    
        for line in infile:
            #line = line.replace(',','')
            line = line.lstrip("[").rstrip("],\n")
            print(line)
    
        infile.close()
    
    read_file("matrix.txt")
    

    As for the first part modified function-

    def write_data_matrix(filename, in_list):
        outfile = open(filename, "w")
    
        for listitem in in_list:
            outfile.write(f"{' '.join(list(map(str, listitem)))}\n")       #Works
                                              
        outfile.close()