首页 > 解决方案 > 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!

标签: pythonlistenumerate

解决方案


您当前正在循环中打开和关闭文件,这是根本原因。

使用withwhich 自动处理打开和关闭文件并将for循环放在它下面:

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

推荐阅读