user3435341
user3435341

Reputation: 51

Write a complete list into a text file in Python

I got a list like this that I got reading a temporary text file before.

['Usain','Jamaican','9','2','0'] 

But now I need to write this list into a new text file that contains a list with lists. The text file should look like this:

  [['Usain','Jamaican','9','2','0'], ['Christopher', 'Costarican', '0','1',2']] 

I've tried to write the list into a text file, but I just import the elements on the list and write them as newlines.

my code looks like this

  def terminar():
    with open('temp.txt', 'r') as f:
      registroFinal = [line.strip() for line in f]
    final = open('final.txt','a')
    for item in registroFinal:
      final.write("%s\n" % item)
    os.remove('temp.txt') 

Upvotes: 0

Views: 162

Answers (1)

AChampion
AChampion

Reputation: 30258

You can use json to dump out the list of lists:

import json
with open('final.txt','a') as final:
    json.dump(registroFinal, final)

You would load this in with json.load(). Otherwise you could use repr(registroFinal) to write out the representation into a file. How is this data going to be used? If you plan to read it back into a python object I would favour the json approach.

Python also has the facility to manage temporary files, see tempfile module

Upvotes: 1

Related Questions