2016-09-30 62 views
0

我正在嘗試在文件中寫入列表。我用:使用Python將文件列表寫入文件

studentFile = open("students1.txt", "w") 
for ele in studentList: 
    studentFile.write(str(ele) + "\n") 
studentFile.close() 

結果,產量爲:

['11609036', 'MIT', 'NE'] 

['11611262', 'MIT', 'MD'] 

['11613498', 'BIS', 'SA'] 

代替:

11609036 MIT NE 

11611262 MIT MD 

11613498 BIS SA 

我怎樣才能解決呢?

回答

4

使用.join每個子列表轉換爲字符串:

studentFile.write(' '.join(ele) + "\n") 

您可能會發現with聲明,創建一個上下文管理開一個更清潔的替代,寫入和關閉文件:

with open("students1.txt", "w") as student_file: 
    for ele in studentList: 
     student_file.write(' '.join(ele) + "\n") 

項目之間的空間可以通過修改' '或使用標籤間距,如'\t'.join

+0

謝謝。它工作完美。 – Dennis

0

studentList列表如何顯示?我懷疑它是一個嵌套列表,你需要另一個循環來挑選單個元素。

studentList = [['11609036', 'MIT', 'NE'], 
       ['11611262', 'MIT', 'MD'], 
       ['11613498', 'BIS', 'SA']] 

studentFile = open("students1.txt", "w") 
for student in studentList: 
    for ele in student: 
     studentFile.write(str(ele) + "\t") 
    studentFile.write("\n") 
studentFile.close()