0

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.

2
Contributors
2
Replies
3
Views
8 Years
Discussion Span
Last Post by Ene Uran
0

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')
0

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()
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.