Hi, I'm having a bit of a problem outputting to a file. I am trying to output each element of a list into a document on a new line and I can only get it to work when all the items in the list are on the same line.

The code I am using is:

book=['1234', '1235', '1236', '1237', '1238']

s=str(book)

for a in book:
	f=open('/home/tandberg/booklist', 'a')
	f.write(a)

I have tried using the '\n' in a number of different ways but can't get it to work properly.

Dani AI

Generated

Good catch by — the missing line breaks come from not writing a newline. Opening the file inside the loop (as in the original post) works but is inefficient and can cause subtle problems. is correct to open the file once, but be aware that mode "w" truncates the file while "a" appends to it.

A concise, more pythonic way is to open the file with a context manager and write all lines in one operation:

with open('/home/tandberg/booklist', 'a') as f:
    f.writelines(item + '\n' for item in book)

Or, if you want to replace the file and the list fits comfortably in memory:

with open('/home/tandberg/booklist', 'w') as f:
    f.write('\n'.join(str(x) for x in book) + '\n')

Notes and troubleshooting tips:

  • Convert non-string items with str() or map(str, ...) before joining/writing.
  • writelines() does not add newlines automatically, so include '\n'.
  • For very large lists prefer streaming (generator + writelines) over join to avoid high memory use.
  • In Python 3 specify encoding='utf-8' in open() if you have non-ASCII text. In very old Python 2.5 you would need from __future__ import with_statement to use with.
  • If multiple processes write to the same file concurrently, use file locking to avoid corruption.

Python's file I/O docs provide more details: Reading and writing files.

hi, I have now solved the problem using:

book=['1234', '1235', '1236', '1237', '1238']

s=str(book)

for a in book:
	f=open('/home/tandberg/booklist', 'a')
	f.write(a + '\n')

Just for the sake of being pythonic:

book = ['1234', '1235', '1236', '1237', '1238']
# you only need to open the file once
f = open('/home/tandberg/booklist', 'w')
for a in book:
	f.write(a + '\n')
f.close()
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.