保存到文本文件-Python时,列表中的所有项都会重复

保存到文本文件-Python时,列表中的所有项都会重复,python,list,io,Python,List,Io,我有一个函数,它获取一个列表,将其转换为字符串,并将其输出到一个.txt文件,但当我检查文本文件时,它将每个条目加倍。我一直在寻找答案,但找不到答案,如果以前有人问过,我表示歉意。 我的代码: workers = ["John","Mark"] # Prints list of employees to file def printAllWorkers(): strList = str(workers).strip('[]') with open('EmployeeList.t

我有一个函数,它获取一个列表,将其转换为字符串,并将其输出到一个.txt文件,但当我检查文本文件时,它将每个条目加倍。我一直在寻找答案,但找不到答案,如果以前有人问过,我表示歉意。 我的代码:

workers = ["John","Mark"]

# Prints list of employees to file
def printAllWorkers():
    strList = str(workers).strip('[]')
    with open('EmployeeList.txt','w') as file:
        for item in workers:
            file.write(strList)
因此,列表应该显示“John”、“Mark”,而不是“John”、“Mark”、“John”、“Mark”

我要么需要一种只输出列表一次的方法(首选),要么获取文本文件并删除任何重复项


谢谢

事实上,在每次迭代中,您都在编写整个列表
strList
,您可以按如下方式修复它:

workers = ["John","Mark"]

# Prints list of employees to file
def printAllWorkers():
    with open('EmployeeList.txt','w') as file:
        file.write(', '.join(workers))

您将创建的字符串写入两次。不要遍历worker并为每个worker编写整个输出。只做一次:

def printAllWorkers():
    strList = str(workers).strip('[]')
    with open('EmployeeList.txt','w') as file:
        file.write(strList)
文件内容:

'John', 'Mark'

将write命令从for循环中取出,它会显示两次,因为它位于一个有两个条目的循环中,这是因为您在最后一行告诉程序将列表每项写入文件一次。将file.write(strlist)中的strlist替换为item,它将按预期工作


为了清楚起见,您的最后一行需要是file.write(item)

只需删除for循环,因为您在workers列表中的ever元素上迭代了2个元素,并将strList输出了两次

workers = ["John","Mark"]

# Prints list of employees to file
def printAllWorkers():
    strList = str(workers).strip('[]')
    with open('EmployeeList.txt','w') as file:
        file.write(strList)

您可以继续使用相同的代码,但将
file.write(strList)
替换为
file.write(item)
。您正在迭代,但正在编写列表,而不是迭代值

要么就这样做:

workers = ["John","Mark"]

    def printAllWorkers():
        #strList = str(workers).strip('[]')
        with open('EmployeeList.txt','w') as file:
            for item in workers:
                file.write(item)

不完全是这样,因为OP需要一个逗号和两个项目之间的一个空格。这表明我还有很多东西要学。谢天谢地,其他人提供了更全面的答案。谢谢你指出。很清楚我在找什么,我知道哪里出了问题!干杯