如何在python中将附加列表存储到.txt文件中

2024-04-24 22:08:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个列表,是一个附加项目的列表

if words[0] == "[" or words[len(words)-1] == "]":
            if words in combinations1:
                line.append(words)

当我试图把这个列表放到一个文件中时,我只能得到列表中的最后一项。你知道吗

我将其写入文件的代码是:

with open("file.txt", "w") as output_file:
                    output_file.write(str(line))

我需要将所有列表项写入文件。怎么做


Tags: or文件项目代码in列表outputlen
3条回答

试试这个:

with open("file.txt", "w") as output_file:
    output_file.write(" ".join(words))

另外,在if语句中,您不需要调用len,只需使用-1对列表进行索引,就可以得到列表的最后一个元素,如:if words[0] == "[" or words[-1] == "]"。你知道吗

open("neededfile.txt","w").write("\n".join([str(content) for content in sendable]))

这个代码片段只在一行中完成,基本上是将各个条目连接起来。 如果您的项不是string数据类型,则使用str()可以工作。你知道吗

试试这个:

with open("file.txt", "w") as output_file:
    for word in line:
        output_file.write(word)

如果您想将所有单词放在不同的行中,它会将它们放在文件的一行中:

with open("file.txt", "w") as output_file:
    for word in line:
        output_file.write(word + '\n')

如果你想让它们排成一行,中间留一个空格:

with open("file.txt", "w") as output_file:
        output_file.write(line.join(' '))

相关问题 更多 >