0

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?

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.