Hi

I want to write some variables into a file to be readable by excel. I used a loop like this to write the calculated "x" variable into the file. It works but the problem is that I get all the numbers in one line. I'm wondering how can I get numbers in seperate lines.

Here is the code:
---------------------------------------------------------------------------
data1 = []
x_org = []
locx = open('C:\Temp\Loc', 'w')
for i in range(9):
data1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
x_org.append(data1)
x = str(x_org)
locx.writelines(x)
locx.close()
----------------------------------------------------------------------------

When you run this code, you get "123456789" in the Loc file. But I need the numbers in seperate lines, like:
1
2
3
4
5
6
7
8
9


Thanks

Nima

Rember use code tag.

data1 = []
x_org = []
locx = open('test.txt', 'w')
for i in range(9):    
    x_org.append(i)
locx.write('\n'.join([str(i) for i in x_org]))
locx.close()

Can break it up it little so it`s easier to understand.

>>> l = [1, 2, 3, 4, 5, 6, 7, 8]
>>> #We have a list of integer,we much convert into string
>>> #With python List Comprehensions
>>> [str(i) for i in l]
['1', '2', '3', '4', '5', '6', '7', '8']
>>> #Or in a functional style with map
>>> map(str, l)
['1', '2', '3', '4', '5', '6', '7', '8']
>>> #Then join it into a string with \n(new line character)
>>> '\n'.join([str(i) for i in l])
'1\n2\n3\n4\n5\n6\n7\n8'
>>> '\n'.join(map(str, l))
'1\n2\n3\n4\n5\n6\n7\n8'
>>>

locx = open('C:\Temp\Loc', 'w')

Use C:/Temp/test.txt or C:\\Temp\\test.txt and you need a file name loc.txt?
\ Can be used as an Escape Characters an file will not be found.

Edited 5 Years Ago by snippsat: n/a

Here you are richiekid ;) Concised version of the whole code.

with open('test.txt', 'w') as locx:
    locx.write('\n'.join(str(i) for i in range(9)))

Edited 5 Years Ago by pyTony: n/a

ha ha .... i was emphasizing on snippsat's explanations.

He was a good teacher. Expalined very well and i think every newbie will just understand what went on.

Hay tonyjv...
wasnt you who complained about my list comp. on the other post that newbie will not understand nd read??... ;)
Tonyjv in love at 9 ;)
Hay happy new year buddy.

This article has been dead for over six months. Start a new discussion instead.