【问题标题】:How can I append to the new line of a file while using write()?如何在使用 write() 时追加到文件的新行?
【发布时间】:2012-11-16 01:59:05
【问题描述】:

在 Python 中: 假设我有一个循环,在每个循环中我生成一个具有以下格式的列表: ['n1','n2','n3'] 在每个周期之后,我想将生成的条目附加到文件中(其中包含前一个周期的所有输出)。我该怎么做?

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

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

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

    当然你可以把它写成一个文件,比如,在将它转换为字符串之后:

    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)
    

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

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

    【讨论】:

      【解决方案2】:

      f=open(file,'a') 第一个是文件的路径,第二个是模式,'a'是追加,'w'是写,'r'是读,等等 我的意见,你可以使用 f.write(list+'\n') 循环写一行,否则你可以使用 f.writelines(list),它也起作用。

      【讨论】:

        【解决方案3】:

        希望对您有所帮助:

        lVals = []
        with open(filename, 'a') as f:
            for x,y,z in zip(range(10), range(5, 15), range(10, 20)):
                lVals.append([x,y,z])
                f.write(str(lVals[-1]))
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-06-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-06-09
          • 2012-05-10
          • 2020-01-23
          相关资源
          最近更新 更多