Search code examples
pythonlistenumerate

Python read/write file exercise. How to print a list to a text file


New to python. Would anyone know how to make it so the text file would have an output of this enumerated list? I currently can only see it happen if it prints to console, but can't make it print to that format in text file.

For example (I know this isn't right format but just trying to show expected output) this prints out to the console, but not to file.

tv_characters = ["Will Byers", "Tyrion Lannister", "Oliver Queen", "Jean Luc Picard", "Malcom Reynolds", "The Doctor", "Sam Winchester", "Sherlock Holmes"]

for index , character in enumerate(tv_characters):
  f = open("text", "w")
  print("{0}: {1}\n".format(index+1, character))

It's supposed to be having the print functionality when set up like this but this only has an output of the last name in list.

tv_characters = ["Will Byers", "Tyrion Lannister", "Oliver Queen", "Jean Luc Picard", "Malcom Reynolds", "The Doctor", "Sam Winchester", "Sherlock Holmes"]

# Write out my character list to a file called "text"
for index , character in enumerate(tv_characters):
  f = open("text", "w")
  f.write("{0}: {1}\n".format(index+1, character))
  f.close()

Thank you in advance!


Solution

  • You are currently opening & closing the file within the loop, which is the root cause.

    Use with which automatically takes care of opening and closing the file and put for loop under it:

    tv_characters = ['Will Byers', 'Tyrion Lannister', 'Oliver Queen', 'Jean Luc Picard', 'Malcom Reynolds', 'The Doctor', 'Sam Winchester', 'Sherlock Holmes']
    with open('text.txt', 'w') as f:
        # Write out my character list to a file called 'text'
        for index, character in enumerate(tv_characters):
          f.write(f'{index+1}: {character}\n')