fredericoamigo
fredericoamigo

Reputation: 129

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 :-)

Upvotes: 0

Views: 918

Answers (2)

Nir H.
Nir H.

Reputation: 550

In order to get the result you want, you have to fix the code at two places:

  1. The line of code:

    outfile.write(f"{listitem},\n")
    

    puts a redundant comma at the end of each line. It should be:

    outfile.write(f"{listitem}\n")
    
  2. When reading the file, you try to strip the brackets. However, the closing bracket (']') is not the last character in the line, the new line character is. So the line:

     inje = line.strip("[").strip("]").split(",")  
    

    should be:

     inje = line.strip("\n[]").split(",")
    

Now that we have made your code work, let's discuss a little bit the concept behind it. What you are trying to do is called serialization and deserialization, namely the process of converting an in-memory object into a serial representation that can be stored on a a storage device, and then converting the stored data back to an object. To this end you created your own (pretty logical) serialization method. However, your method has several drawbacks, the biggest one being its lack of generality. Suppose you have, for some reason, to serialize a list of lists of lists, or a completely different type of object like one you created yourself, then you will have to modify your serialization and deserialization functions to accommodate every new type of object.

The right thing to do is to use standard serialization methods which are, usually, efficient and general. Two possible methods are serializing to JSON and serializing to a PICKLE file.

Upvotes: 1

Agnij
Agnij

Reputation: 581

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()

Upvotes: 1

Related Questions