How to write list elements into a tab-separated file?

Anastasia picture Anastasia · May 24, 2018 · Viewed 10.4k times · Source

I have searched the web but I haven't found the answer for my problem:

I have a a dictionary with lists as elements and every list has a different length. For example like that:

dict_with_lists[value1] = [word1, word2, word3, word4]
dict_with_lists[value2] = [word1, word2, word3]

My main problem is, that I want to write the list elements in to a file which should be tab-separated and if the list is finished it should write the new list in a new line.

I found a solution like that:

with open('fname', 'w') as file:
   file.writelines('\t'.join(i) + '\n' for i in nested_list)

But it doesn't only separate the words with tabs but also the characters.

Answer

Martijn Pieters picture Martijn Pieters · May 24, 2018

If nested_list is one of your dictionary values, then you are applying '\t'.join() to the individual words. You'd want to join the whole list:

file.write('\t'.join(nested_list) + '\n')

or, if you were to loop over the values of the dictionary:

file.writelines(
    '\t'.join(nested_list) + '\n'
    for nested_list in dict_with_lists.values())

The above uses the file.writelines() method correctly; passing in an iterable of strings to write. If you were to pass in a single string, then you are only causing Python extra work as it loops over all the individual characters of that string to write those separately, after which the underlying buffer has to assemble those back into bigger strings again.

However, there is no need to re-invent the character-separated-values writing wheel here. Use the csv module, setting the delimiter to '\t':

import csv

with open('fname', 'w', newline='') as file:
    writer = csv.writer(file, delimiter='\t')
    writer.writerows(dict_with_lists.values())

The above writes all lists in the dict_with_lists dictionary to a file. The csv.writer() object doesn't mind if your lists are of differing lengths.