在Python中:
假设我有一个循环,在每个循环中我都会产生以下格式的列表:
['n1','n2','n3']
在每个循环之后,我想编写将产生的条目附加到文件(该文件包含先前循环的所有输出)。我怎样才能做到这一点?

另外,有没有办法列出其条目是此循环的输出的列表?即
[[],[],[]]其中每个内部[] = ['n1','n2','n3]等

最佳答案

将单个列表作为行写入文件

将其转换为字符串后,可以肯定地将其写入文件:

with open('some_file.dat', 'w') as f:
    for x in xrange(10):  # assume 10 cycles
        line = []
        # ... (here is your code, appending data to line) ...
        f.write('%r\n' % line)  # here you write representation to separate line


一次编写所有行

关于您的问题的第二部分:


  另外,有没有办法列出其条目是此循环的输出的列表?即[[],[],[]]其中每个内部[] = ['n1','n2','n3']


这也是非常基本的。假设您想一次保存所有内容,只需编写:

lines = []  # container for a list of lines
for x in xrange(10):  # assume 10 cycles
    line = []
    # ... (here is your code, appending data to line) ...
    lines.append('%r\n' % line)  # here you add line to the list of lines
# here "lines" is your list of cycle results
with open('some_file.dat', 'w') as f:
    f.writelines(lines)


将列表写入文件的更好方法

根据您的需要,您可能应该使用更专业的格式之一,而不只是文本文件。除了编写列表表示(可以,但不理想),您可以使用eg。 csv模块(类似于Excel的电子表格):http://docs.python.org/3.3/library/csv.html

关于python - 使用write()时如何追加到文件的新行?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13409324/

10-11 09:25
查看更多