Reputation: 39
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
Upvotes: 1
Views: 3163
Reputation: 18008
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)
Upvotes: 1
Reputation: 3782
If your list is a nested list, you can just use loop to writelines, like this way:
fullpath = ('./data.txt')
outfile = open(fullpath, 'w')
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']]
for result in results:
outfile.writelines(result)
outfile.write('\n')
outfile.close()
Besides, remember close the file.
Upvotes: 1
Reputation: 3723
If you can gather all those strings into a single big list, you could loop through them.
I'm not sure where results
came from from your code, but if you can put all those strings in a single big list (maybe called masterList), then you could do:
fullpath = ('O:/Location/complete.txt')
outfile = open(fullpath, 'w')
for item in masterList:
outfile.writelines(item)
Upvotes: 0