The csv.writer() object doesn't mind if your lists are of differing lengths. The above writes all lists in the dict_with_lists dictionary to a file. Writer.writerows(dict_with_lists.values()) Writer = csv.writer(file, delimiter='\t') With open('fname', 'w', newline='') as file: Use the csv module, setting the delimiter to '\t': import csv However, there is no need to re-invent the character-separated-values writing wheel here. 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. The above uses the file.writelines() method correctly passing in an iterable of strings to write. Or, if you were to loop over the values of the dictionary: file.writelines(įor nested_list in dict_with_lists.values()) Example 1: Creating a CSV file and writing data row-wise into it using writer class. The most common method to write data from a list to CSV file is the writerow () method of writer and DictWriter class. You'd want to join the whole list: file.write('\t'.join(nested_list) '\n') A CSV file is a bounded text format which uses a comma to separate values. If nested_list is one of your dictionary values, then you are applying '\t'.join() to the individual words.
0 Comments
Leave a Reply. |