【问题标题】:how to store a appended list into a .txt file in python如何将附加列表存储到python中的.txt文件中
【发布时间】:2018-09-25 14:16:00
【问题描述】:

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

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

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

【问题讨论】:

  • 是否要将每个列表条目存储在新行中?
  • 是的,我需要将每个条目存储到文件中的新行中
  • 顺便说一句,words[len(words)-1]words[-1] 相同。

标签: python list file


【解决方案1】:

试试这个:

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

【讨论】:

  • 不起作用!它给出一个输出 - 如果列表是 ['that', 'is', 'the', 'end', '.'] 那么输出类似于“thatistheend”。这个在文件中
  • 您希望该列表的输出是什么?
  • 考虑这些是附加['uh', '[/]', 'not', 'gonna', 'xxx', 'xxx', 'that', 'rabbit', '.'] ['that', 'guy', 'c', '[//]', 'that', 'w', '[/]', 'that', 'rabbit', 'want', 'a', 'balloon', '.'] ['and', 'he', 'is>', '[/]', 'he', 'is', 'going', 'get', '[/]', 'get', 'some', 'money', 'and', 'get', 'a', 'balloon', '!'] ['he', '[/]', 'he', 'get', '[/]', 'he', 'hold', 'it', '.'] ['that', 'is', 'the', 'end', '.']后列表中的项目我需要将列表中名为line的所有项目存储到.txt文件中
  • 男人。它是 5 个列表,而不是一个。你想让它们在那个文件中完全像这样吗?
  • 请解释一下添加后的列表是什么样子的?它是存储在同一个名为 line 的列表中还是存储为 5 个不同的列表?是的,我需要它们完全像这样在一个文件中
【解决方案2】:
open("neededfile.txt","w").write("\n".join([str(content) for content in sendable]))

这段代码sn-p在一行中完成,基本上你加入了各种条目。 如果您的项目不是字符串数据类型,则使用 str() 有效。

【讨论】:

    【解决方案3】:

    试试这个:

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

    另外,在 if 语句中,您无需调用 len,只需使用 -1 索引您的列表即可获取列表的最后一个元素,如下所示:if words[0] == "[" or words[-1] == "]"

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-03-02
      • 1970-01-01
      • 1970-01-01
      • 2011-03-09
      • 1970-01-01
      • 2021-03-30
      • 2016-08-09
      相关资源
      最近更新 更多