【问题标题】:How to print set list to new lines in text file python 3如何将设置列表打印到文本文件python 3中的新行
【发布时间】:2019-04-26 16:43:51
【问题描述】:

基本上我想制作一个程序,它可以读取文本文件,对信息进行处理,然后将不同的信息输出到文件中。

例如; input.txt 包含不同的文本行

然后我用这个转换成列表:

with open("input.txt") as f:
content = f.readlines()
content = [x.strip() for x in content]

然后将列表输出到一个文本文件中,而不是像 ['string', 'string'] 而是换行。

有什么帮助吗???

【问题讨论】:

  • 你试过什么?这听起来像是家庭作业。
  • 我尝试了什么?什么意思?
  • 你做了什么来尝试自己解决问题? @DMMO官方
  • 我已经在网上搜索和堆栈,但我才刚刚开始编码,所以是的

标签: python python-3.x list file file-handling


【解决方案1】:
$ cat input.txt
 HELLO
 WORLD

在 python 中,您可以使用 '\n' 将新行追加到内容中。

   with open("input.txt") as f:
        content = f.readlines()
        content = [x.strip() for x in content]
        content = '\n'.join(content)

【讨论】:

    【解决方案2】:

    读取文件并修改列表中的内容后。该列表可以写回一个文本文件,列表中的每个项目都有新行,如下所示:

    with open('my_file.txt', 'w') as f:
        for item in my_list:
            f.write("%s\n" % item)
    

    【讨论】:

      【解决方案3】:

      你可以像这样创建一个字符串:

      elements_on_new_line = '\n'.join(my_list)
      

      然后你在文件上写下变量'elements_on_new_line'

      这样做

      with open('my file.txt', 'w') as my_file:
          my_file.write(elements_on_new_line)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-03-03
        • 1970-01-01
        • 2017-04-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-06-02
        • 1970-01-01
        相关资源
        最近更新 更多