将嵌套列表写入文本文件?

问题描述 投票:0回答:1

嘿,大家好,我是python新手,如果我运行下面的代码。

test = [['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c']]

with open('listfile.txt', 'w') as file:
    for item in test:
        for i in range(2):
            file.write("%s" % item)
            file.write("\n")

文本文件看起来是这样的:

['a', 'b', 'c']
['a', 'b', 'c']
['a', 'b', 'c']
['a', 'b', 'c']
['a', 'b', 'c']
['a', 'b', 'c']
['a', 'b', 'c']
['a', 'b', 'c']

有什么办法可以让它看起来像这样吗?

a    b    c
a    b    c
a    b    c
a    b    c

先谢谢你,请随时纠正我的编码。

python
1个回答
0
投票

你想在每个项目之间用tab而不是换行。我改变的第二件事是我添加了 file.write("\n") 在内部循环之后,为了在每行之间有一个新的行。最后,我添加了 file.close() 来关闭文件。

test = [['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c']]

with open('listfile.txt', 'w') as file:
    for item in test:
        for i in range(len(item)):
            file.write("%s" % item[i])
            file.write("\t") # having tab rather than "\n" for newline. 
        file.write("\n")
file.close()

0
投票
with open('listfile.txt', 'w') as file:
    file.write('\n'.join(' '.join(map(str, lett)) for lett in test))

这段代码将列表变成一个带有 join然后,通过用一个 \n.

输出是这样的。

a b c
a b c
a b c
a b c

看来你想要的是标签,所以你可以用... ... \t 而不是 ' ':

test = [['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c']]

with open('listfile.txt', 'w') as file:
    file.write('\n'.join('\t'.join(map(str, sl)) for sl in test))

其中输出的是这个。

a   b   c
a   b   c
a   b   c
a   b   c

0
投票

使用 ''.join()

with open('listfile.txt', 'w') as file:
    file.write('\n'.join('  '.join(item) for item in test))
© www.soinside.com 2019 - 2024. All rights reserved.