Dennis
Dennis

Reputation: 3

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?

Upvotes: 0

Views: 71

Answers (2)

Anurag
Anurag

Reputation: 196

How does your studentList list look like? I suspect its a nested list and you need another loop to pick individual elements.

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()

Upvotes: 0

Moses Koledoye
Moses Koledoye

Reputation: 78564

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.

Upvotes: 3

Related Questions