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()) ![]() To write a list into a text file with comma-separated values without brackets, use string.join() method. You'd want to join the whole list: file.write('\t'.join(nested_list) '\n') Write List to File Comma-Separated without Brackets. If nested_list is one of your dictionary values, then you are applying '\t'.join() to the individual words.
0 Comments
Leave a Reply. |