[英]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: 如果列表是嵌套列表,则可以使用loop来写行,如下所示:
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: 假设
results
是一个列表列表:
from itertools import chain
outfile = open(fullpath, 'w')
outfile.writelines(chain(*results))
itertools.chain
will concat the lists into a single list. itertools.chain
将这些列表合并为一个列表。 But writelines
will not write newlines. 但是
writelines
不会写换行符。 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: 我不确定
results
来自哪里,但是如果您可以将所有这些字符串放在一个大列表中(可能称为masterList),则可以执行以下操作:
fullpath = ('O:/Location/complete.txt')
outfile = open(fullpath, 'w')
for item in masterList:
outfile.writelines(item)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.