简体   繁体   中英

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

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.

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)

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM