1

最初这些列表嵌套在另一个列表中。列表中的每个元素都是一系列字符串。

['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

我希望文本文件包含所有结果

4

3 回答 3

1

如果你的列表是一个嵌套列表,你可以使用循环来写行,像这样:

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-10T01:58:30.617 回答
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)
于 2015-02-10T02:00:15.147 回答
0

如果您可以将所有这些字符串收集到一个大列表中,则可以遍历它们。

我不确定results您的代码来自哪里,但是如果您可以将所有这些字符串放在一个大列表中(可能称为 masterList),那么您可以这样做:

fullpath = ('O:/Location/complete.txt')
outfile = open(fullpath, 'w')

for item in masterList:
    outfile.writelines(item)
于 2015-02-10T01:57:14.830 回答