最初,这些列表嵌套在另一个列表中。列表中的每个元素都是一系列字符串。
['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我希望文本文件包含所有结果
发布于 2015-02-10 02:00:15
假设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)发布于 2015-02-10 01:58:30
如果您的列表是嵌套的列表,则只需使用循环来写入基线,如下所示:
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()另外,请记住关闭文件。
发布于 2015-02-10 01:57:14
如果您可以将所有这些字符串收集到一个大列表中,则可以循环遍历它们。
我不知道results来自于您的代码,但是如果您可以将所有这些字符串放在一个大列表中(可能称为masterList),那么您可以这样做:
fullpath = ('O:/Location/complete.txt')
outfile = open(fullpath, 'w')
for item in masterList:
outfile.writelines(item)https://stackoverflow.com/questions/28422756
复制相似问题