0

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

1

2 Answers 2

1

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()
Sign up to request clarification or add additional context in comments.

1 Comment

Aha! I wasn't aware that lstrip() and rstrip() was a thing :-) Thanks for helping me out! Much appreciated!
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.