代码之家  ›  专栏  ›  技术社区  ›  TechGeek

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

  •  0
  • TechGeek  · 技术社区  · 4 年前

    我试图在一个文本文件中记录作为成功求职者入围的员工的姓名,每个人的姓名在文本文件的单独一行中,循环中检查一个计数器索引变量,以告诉程序何时换行和何时不换行。除了我的代码在第一行打印了两个名字,下面是我的逻辑。帮我告诉这个程序在每行上打印一个名字

    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
    
    
    4 回复  |  直到 4 年前
        1
  •  2
  •   Sharmiko    4 年前

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

    file.writelines('\n'.join(applicants))
    
        2
  •  1
  •   GodWin1100    4 年前

    你的错误/问题在你的逻辑中,特别是在你的else块中。
    对于 大卫 您的索引是 1 所以它将进入 else 其他的 阻止您将行写为 el+"\n" 所以 David 正在与添加到同一行 Avery 然后添加新行。我希望这消除了你的疑虑。所以如果在 其他的 file.write("\n"+el) 并且在 elif 也

    另一种方法可以是:-

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

    将在新行上打印姓名。

        3
  •  1
  •   Sreckcep    4 年前

    您只需在每行的开头而不是末尾打印换行符。这样你就不需要解释最后一行了! 您还可以避免索引的递增。

    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)
    
        4
  •  0
  •   Ramachandran Rajasekaran    4 年前
    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")