Dennis Dennis - 2 months ago 6
Python Question

Writing a list into the file by using Python

I am trying to write a list into the file. I used:

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


As a result, the output was:

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

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

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


instead of:

11609036 MIT NE

11611262 MIT MD

11613498 BIS SA


How can I fix it?

Answer

Use .join to convert each sublist into a string:

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

You may find the with statement which creates a context manager a more cleaner alternative for opening, writing to, and closing files:

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

The space in between the items can be increased by modifying ' ' or using tab spacing as in '\t'.join.