Rob
Rob

Reputation: 89

Python - Iterating through a list of list with a specifically formatted output; file output

Sorry to ask such a trivial question but I can't find the answer anyway and it's my first day using Python (need it for work). Think my problem is trying to use Python like C. Anyway, here is what I have:

for i in data:
    for j in i:
        print("{}\t".format(j))

Which gives me data in the form of

elem[0][0]
elem[1][0]
elem[2][0]
...
elem[0][1]
elem[1][1]
...

i.e. all at once. What I really want to do, is access each element directly so I can output the list of lists data to a file whereby the elements are separated by tabs, not commas.

Here's my bastardised Python code for outputting the array to a file:

k=0
with open("Output.txt", "w") as text_file:
    for j in data:
        print("{}".format(data[k]), file=text_file)
        k += 1

So basically, I have a list of lists which I want to save to a file in tab delimited/separated format, but currently it comes out as comma separated. My approach would involve reiterating through the lists again, element by element, and saving the output by forcing in the the tabs.

Here's data excerpts (though changed to meaningless values)

data
['a', 'a', 306518, ' 1111111', 'a', '-', .... ]
['a', 'a', 306518, ' 1111111', 'a', '-', .... ]
....

text_file
a    a    306518    1111111    a    -....
a    a    306518    1111111    a    -....
....

Upvotes: 2

Views: 84

Answers (3)

user3012759
user3012759

Reputation: 2095

I think this should work:

with open(somefile, 'w') as your_file:
    for values in data:
        print("\t".join(valeues), file=your_file)

Upvotes: 0

gkusner
gkusner

Reputation: 1244

if data is something like this '[[1,2,3],[2,3,4]]'

for j in data:
    text_file.write('%s\n' % '\t'.join(str(x) for x in j))

Upvotes: 0

John Zwinck
John Zwinck

Reputation: 249173

for i in data:
    print("\t".join(i))

Upvotes: 1

Related Questions