如何在综合嵌套列表中向文本文件添加换行符?

How to add newline to text file in comprehensive nested list?

我有一个嵌套列表:

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()

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

修复相当简单:

\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()

第二种方法 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)。

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

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()