最初列表嵌套在另一个列表中。列表中的每个元素都是一系列字符串。
['aaa664847', 'Completed', 'location', 'mode', '2014-xx-ddT20:00:00.000']
我加入了列表中的字符串,然后附加到结果中。
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']
我希望将每个列表写入文本文件。列表的数量可以变化。
我目前的代码:
fullpath = ('O:/Location/complete.txt')
outfile = open(fullpath, 'w')
outfile.writelines(results)
只返回文本文件中的第一个列表:
aaa664847, Completed, location, mode, 2014-xx-ddT20:00:00.000
我希望文本文件包含所有结果
答案 0 :(得分:1)
如果你的列表是嵌套列表,你可以像这样使用循环到writelines:
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()
此外,请记得关闭文件。
答案 1 :(得分:1)
假设results
是列表清单:
from itertools import chain
outfile = open(fullpath, 'w')
outfile.writelines(chain(*results))
itertools.chain
会将列表连成一个列表。
但writelines
不会写新内容。为此你可以这样做:
outfile.write("\n".join(chain(*results))
或者,显而易见(假设结果中的所有列表只有一个字符串):
outfile.write("\n".join(i[0] for i in results)
答案 2 :(得分:0)
如果你可以将所有这些字符串收集到一个大的列表中,你可以循环遍历它们。
我不确定results
来自您的代码,但是如果您可以将所有这些字符串放在一个大的列表中(可能称为masterList),那么您可以这样做:
fullpath = ('O:/Location/complete.txt')
outfile = open(fullpath, 'w')
for item in masterList:
outfile.writelines(item)