【问题标题】:Writing a whole list AS SUCH to a text file in Python [duplicate]在Python中将整个列表写入文本文件[重复]
【发布时间】:2020-10-17 12:44:29
【问题描述】:

在 python 中,我不想将每个元素都写入文件,而是整个列表。这意味着文本文件应如下所示:

["elem1", "elem2", "elem3"]
["elem1", "elem2", "elem3"]
["elem1", "elem2", "elem3"]

这是将列表中的每个元素写入文本文件 (Writing a list to a file with Python) 的示例。但正如我所说,我不需要这个。

谁能帮帮我?

【问题讨论】:

    标签: python list writetofile


    【解决方案1】:

    这里有三种方式:

    import json
    
    
    l = ["elem1", "elem2", "elem3"]
    print(str(l))
    print(repr(l))
    print(json.dumps(l))
    

    打印:

    ['elem1', 'elem2', 'elem3']
    ['elem1', 'elem2', 'elem3']
    ["elem1", "elem2", "elem3"]
    

    当然,您可以将 print 语句指向输出文件。

    【讨论】:

      【解决方案2】:

      使用list.__str__()从原始答案更新

      您可以通过使用str() 来实现这一点,如下所示。

      l = [1, 'this', 'is', 'a', 'list']
      
      with open('example.txt', 'w') as f:
          f.write(str(l))
      

      example.txt的内容

      [1, 'this', 'is', 'a', 'list']
      

      【讨论】:

      • str(l) 是 Pythonic 方式 - 通常不直接调用双下划线 (dunder) 方法。
      • @snakecharmerb 点对点,更 Pythonic。感觉一个傻瓜直接跳到一个dunder!谢谢你把我拉起来:) 答案更新了。
      【解决方案3】:

      你可以这样试试:

      with open('FILE.txt', 'w+') as f:
          f.write(myList.__str__())
      

      【讨论】:

      • str(myList) 是 Pythonic 方式 - 通常不直接调用双下划线 (dunder) 方法。
      猜你喜欢
      • 2013-09-19
      • 2018-06-07
      • 2013-02-18
      • 2014-11-22
      • 2023-03-17
      • 2021-02-24
      • 1970-01-01
      • 2018-02-02
      • 2020-04-20
      相关资源
      最近更新 更多