如何在文本文件中逐行打印数组的内容?



我试图记录在文本文件中每个人的名字的文本文件中被列为成功申请人的员工的名字,在文本文件上的单独一行中,有一个计数器索引变量,在循环内检查,告诉程序何时断行,何时不断行。除了我的代码在第一行打印两个名字之外,下面是我的逻辑。帮我告诉这个程序每行打印一个名字

applicants = ["Timothy", "David", "Mary", "Drew", "Titus", "Samuel","Avery"]
# sort the names of the applicants
applicants.sort()
#initialize the index variable
index = 0
#write the name of each applicant to the file
for el in applicants:  # write the name of the worker to the text file
if index == 0:  # this is the first line no need for a line break
file.write(el)
# increment the index for later iterations
index += 1
elif index == len(names)-1:#  this is the last line no need for a line break
file.write(el)
index += 1
else:  # these are the middle lines and it is essential to break a line
file.write(el+"n")
index += 1

您可以使用更python的方法来实现所需的输出。

file.writelines('n'.join(applicants))

你的错误/问题在你的逻辑中,特别是在你的else块中。
forDavid你的索引是1,所以它将进入else块,在else块中,你将行写为el+"n",所以David被添加到与Avery相同的行,然后添加新行。我希望这能消除你的疑虑。因此,如果在else块,你可以在file.write("n"+el)elif

另一种方法是:-

with open("Fiddle.txt","w") as file:
file.writelines("n".join(applicants)) # will join elements of list with "n"

将在新行上打印名称。

您应该在每行的开头而不是末尾打印换行符。这样你就不需要考虑最后一行了!您还可以去掉索引的增量。

for el in applicants:  # write the name of the worker to the text file
if index == 0:  # this is the first line no need for a line break
file.write(el)
# increment the index for later iterations
index += 1
else:  # these are the middle lines and it is essential to break a line
file.write("n"+el)
applicants = ["Timothy", "David", "Mary", "Drew", "Titus", "Samuel","Avery"]
# sort the names of the applicants
applicants.sort()
with open("sample.txt", "w+") as f:
for name in applicants:
f.write(str(name) + "n")

最新更新