Reputation: 87
I have a list that looks like
[["a","b","c","d"],["e","f","g","h"],["i","j","k","l"]]
How can I convert this list of list into a text file that looks like
a b c d
e f g h
i j k l
It seemed straightforward but none of the solution on the web seemed concise and elucidating enough for dummies like me to understand.
Thank you!
Upvotes: 5
Views: 301
Reputation: 43169
Praise the power of comprehensions here:
lst = [["a","b","c","d"],["e","f","g","h"],["i","j","k","l"]]
out = "\n".join([" ".join(sublist) for sublist in lst])
print(out)
This yields
a b c d
e f g h
i j k l
Or, longer, maybe more understandable:
for sublist in lst:
line = " ".join(sublist)
print(line)
.format()
:
lst = [["a","b","cde","d"],["e","f","g","h"],["i","j","k","l"]]
out = "\n".join(["".join("{:>5}".format(item) for item in sublst) for sublst in lst])
print(out)
Which would yield
a b cde d
e f g h
i j k l
Upvotes: 6
Reputation: 7622
More one liners, for fun (Don't write code like this btw!)
with open('/tmp/my_file2.txt', 'w') as thefile: thefile.write('\n'.join(' '.join(el for el in l1) for sub in sub))
Upvotes: 1
Reputation: 11550
There's csv for that.
l = [["a","b","c","d"],["e","f","g","h"],["i","j","k","l"]]
with open("test.csv", 'w', encoding="utf-8", newline="") as f:
writer = csv.writer(f, delimiter=' ')# or "\t", default is coma.
writer.writerows(l)
Upvotes: 1
Reputation: 59978
To write in a file in that format you can use join
like this :
array = [['a','b','c','d'],['e','f','g','h'],['i','j','k','l']]
# create a file if not exist and open it
file = open('testfile.txt', 'w')
# for each element in the array
for a in array:
# convert each sub list to a string, and write it in the file, note break line '\n'
file.write(' '.join(a) + '\n')
# close the file when you finish
file.close()
result :
To avoid the break line in the end you can use :
breakLine = ''
for a in array:
file.write(breakLine + ' '.join(a))
# Use break line after the first write
breakLine = '\n'
file.close()
result 2
Upvotes: 2
Reputation: 119
Posting just to highlight the steps you need to take
l = [['a','b','c','d'], ['e', 'f', 'g', 'h'], ['i', 'j', 'k', 'l']]
with open('my_file.txt', 'w') as f:
for sub_list in l:
for elem in sub_list:
f.write(elem + ' ')
f.write('\n')
Upvotes: 4
Reputation: 8287
You can use list comprehension with newline:
'\n'.join(' '.join(item) for item in ls)
Upvotes: 4