【问题标题】:How to add newline to text file in comprehensive nested list?如何在综合嵌套列表中向文本文件添加换行符?
【发布时间】:2019-09-24 10:01:40
【问题描述】:

我有一个嵌套列表:

A = [['a', 'b', 'c', 'd', 'e'], ['a', 'a', 'b', 'c'], ['b', 'c'], ['a', 'd']]

我想将列表 A 保存到多个文本文件中,每个文本文件限制为 2 个嵌套列表。

所以输出应该是这样的:

small_file_2.txt:

a
b
c
d
e

a
a
b
c

small_file_4.txt:

b
c

a
d

我试过这段代码:

lines_per_file = 2
for lineno, line in enumerate(A):
    if lineno % lines_per_file == 0:
        if smallfile:
           smallfile.close()
        small_filename = 'small_file_{}.txt'.format(lineno + lines_per_file)
        smallfile = open(small_filename, "w")
     smallfile.write('\n'.join(str(x) for x in line)+'\n')         
smallfile.close()

不幸的是,文本文件中的输出与我预期的不同。它不会在每个新的嵌套列表之后打印换行符。

【问题讨论】:

  • 请修正缩进。 smallfile.write 缩进错误。

标签: python list-comprehension nested-lists


【解决方案1】:

修复相当简单:

\n.join([]) 在每个项目之间添加\n,但不是在之前和之后。您添加的第一个\n 只是在之后添加了一个。如果你想把它分开,你需要第二个。

lines_per_file = 2
for lineno, line in enumerate(A):
    if lineno % lines_per_file == 0:
        if smallfile:
           smallfile.close()
        small_filename = 'small_file_{}.txt'.format(lineno + lines_per_file)
        smallfile = open(small_filename, "w")
    smallfile.write('\n'.join(str(x) for x in line)+'\n\n')         # <= add a second \n
smallfile.close()

【讨论】:

    【解决方案2】:

    第二种方法,with,末尾没有空行:

    lines_per_file = 2
    for lineno in range(0, len(A), lines_per_file):
        small_filename = 'small_file_{}.txt'.format(lineno + lines_per_file)
        with smallfile = open(small_filename, "w"): #this will close the file by itself
            smallfile.write('\n\n'.join('\n'.join(str(x) for x in A[current])) for current in range(lineno, min(lineno+lines_per_file, len(A)))
    

    让我们解释一下魔法:

    for lineno in range(0, len(A), lines_per_file):
    

    我们将从 0 到 lines_per_file-1 的所有行,然后从 lines_per_file 到 2*lines_per_file-1...直到最后。

    '\n'.join(str(x) for x in A[current])
    

    这是您使用的,但我们直接从 A 调用该行。将一行解析为多行中的单个字符。

    '\n\n'.join(...)
    

    解析的行之间会有两个换行符 - 这意味着你想要一个空行。

    for current in range(lineno, min(lineno+lines_per_file, len(A))
    

    正如我所说,我们从 lineno(即:0、lines_per_file、2*lines_per_file...)中提取行,直到下一步。或者直到 A 结束,以较短者为准(这就是为什么有 min)。

    【讨论】:

      【解决方案3】:

      以下代码可以根据您的要求正常工作。

      lines_per_file = 2
      for lineno, line in enumerate(A):
          if lineno % lines_per_file == 0:
              small_filename = 'small_file_{}.txt'.format(lineno + lines_per_file)
          smallfile = open(small_filename, "a")
          smallfile.write('\n'.join(str(x) for x in line)+'\n')
          smallfile.write('\n')
          smallfile.close()
      smallfile.close()
      

      【讨论】:

        猜你喜欢
        • 2019-01-11
        • 1970-01-01
        • 2019-01-31
        • 2020-11-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-06-01
        相关资源
        最近更新 更多