0

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') 
1
  • final.write("%s\n" % repr(item)) ? Commented Oct 20, 2015 at 6:23

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

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.