2016-03-14 16 views
2

我有一個函數,它接受一個列表,將其轉換爲一個字符串,並將其輸出到一個.txt文件中,但是當我檢查文本文件時,條目。我已經搜索了一個答案,但找不到一個,如果之前已經問過這個問題,我表示歉意。 我的代碼:當保存到文本文件時,列表中的所有項都被複制 - Python

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) 

所以列表應該顯示「約翰」,「馬克」,而是顯示「約翰」,「馬」,「約翰」,「馬克」

我要麼需要一個方式只輸出一次(首選)或採取文本文件並刪除任何重複。

謝謝!

回答

0

你寫你創建的字符串的兩倍。不要遍歷工作人員併爲每個工作人員編寫整個輸出。難道它只有一次:

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

文件內容:

'John', 'Mark' 
+0

Exacly什麼,我一直在尋找,我看我哪裏錯了!乾杯! – Dracharon

0

事實上,你在每次迭代寫入整個列表strList,你可以按如下修正:

workers = ["John","Mark"] 

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

就拿寫命令出來的for循環,它顯示了兩次,因爲你擁有了它在具有2項

0
循環

這是因爲您要在最後一行中告訴程序將每個項目的列表寫入文件一次。將item.write(strlist)中的strlist替換爲item,它將按預期工作。

要清楚你的最後一行必須file.write(項目)

+0

不完全,因爲OP需要逗號和項目之間的空格。 –

+0

韋爾普,錯過了。表明我仍有很多需要學習的東西。幸好其他人提供了更全面的答案。感謝您指出。 – TheCog

0

只需卸下for循環,因爲你是遍歷在工人曾經元素名單,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) 
0

您可以繼續使用相同的代碼,但可以用file.write(item)代替file.write(strList)。您正在迭代,但寫入列表而不是迭代值。

要麼去這個:

workers = ["John","Mark"] 

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