python - 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!
解决方案
您当前正在循环中打开和关闭文件,这是根本原因。
使用with
which 自动处理打开和关闭文件并将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')
推荐阅读
- javascript - 在 Firefox 中区分允许位置访问和允许位置访问(记住)
- css - CSS - 带有透明文本的按钮
- javascript - 遍历js es6 map中的指定范围
- css - 为什么我的 CSS3 加载动画不能在移动设备上运行?
- ms-access - 如何对主要包含数字和点的文本列进行排序
- python-3.x - ssh 使用 python 托管
- arrays - Julia 缺少数组构造函数?
- python - 比较字典内列表中任意数量的日期
- javascript - 是否从块页面加载动态加载脚本?
- firebase - Firebase 数据库不允许用户电子邮件的子字符串