【发布时间】:2021-05-23 09:53:47
【问题描述】:
我需要将此列表写入文件并输出名称,每个名称都换行。
我试试:
names = ["John", "Oscar", "Jacob"]
file = open("names.txt", 'w+')
with file as f:
f.write("%s\n" % i for i in names)
file.close()
file = open('names.txt', 'r')
print(file)
file.close()
我得到:
TypeError: write() argument must be str, not generator
我也试过了:
names = ["John", "Oscar", "Jacob"]
file = open("names.txt", 'w+')
for i in names:
file.write(i + '\n')
file.close()
file = open('names.txt', 'r')
print(file)
file.close()
我得到:
<_io.TextIOWrapper name='names.txt' mode='r' encoding='cp1252'>
我使用 Windows Powershell 和手机上的 SoloLearn 应用进行了尝试。我做错了什么?!
【问题讨论】:
-
第二种方法是正确的。唯一的问题是您打印的是文件对象而不是其内容。试试
print(file.read())而不是print(file)。