Search code examples
pythontextwritefile

Write multiple lists to text file in python - 2.7


originally the lists was nested within another list. each element in the list was a series of strings.

['aaa664847', 'Completed', 'location', 'mode', '2014-xx-ddT20:00:00.000']

I joined the strings within the list and then append to results.

results.append[orginal] 

print results

['aaa664847, Completed, location, mode, 2014-xx-ddT20:00:00.000']
['aaa665487, Completed, location, mode, 2014-xx-ddT19:00:00.000']
['aaa661965, Completed, location, mode, 2014-xx-ddT18:00:00.000']
['aaa669696, Completed, location, mode, 2014-xx-ddT17:00:00.000']
['aaa665376, Completed, location, mode, 2014-xx-ddT16:00:00.000']

I am looking to write each list to a text file. The number of lists can vary.

My current code:

fullpath = ('O:/Location/complete.txt')
outfile = open(fullpath, 'w')
outfile.writelines(results)

returns only the first list in the text file:

aaa664847, Completed, location, mode, 2014-xx-ddT20:00:00.000

I would like the text file to include all results


Solution

  • Assuming results is a list of lists:

    from itertools import chain
    outfile = open(fullpath, 'w')
    outfile.writelines(chain(*results))
    

    itertools.chain will concat the lists into a single list. But writelines will not write newlines. For that you can do this:

    outfile.write("\n".join(chain(*results))
    

    Or, plainly (assuming all list inside results have only one string):

    outfile.write("\n".join(i[0] for i in results)