Python读/写文件练习。如何将列表打印到文本文件

时间:2019-11-10 02:58:25

标签: python list enumerate

python的新手。谁知道该怎么做,以便文本文件具有此枚举列表的输出?我目前只能看到它会打印到控制台,但无法使其以文本文件的格式打印。

例如(我知道这不是正确的格式,而只是试图显示预期的输出),这会打印到控制台,而不是文件。

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

这样设置时应该具有打印功能,但这仅输出列表中的姓氏。

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

提前谢谢!

2 个答案:

答案 0 :(得分:3)

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

使用with会自动处理打开和关闭文件并将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')

答案 1 :(得分:0)

我无法发表评论,因此表示歉意。如果我正确理解了您的问题,这将会有所帮助! (python3)

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

# no need to open and close over and over
f = open("text", "w")

for index, character in enumerate(tv_characters) : f.write(f"{index+1}: {character}\n") # basic one liner

# will close once it's done, cleans up code
f.close()