【问题标题】:Python Writing a List into a Text Document With formattingPython将列表写入带有格式的文本文档
【发布时间】:2021-11-04 04:44:38
【问题描述】:

我需要能够让 python 创建一个以某种方式显示列表的新文本文档,但我不确定如何在文本创建区域中使用格式

def write_to_file(filename, character_list):
### Using a while loop to iterate over the list of lists (characters).
index = 0
while index < len(character_list):
    with open("new_characters.txt", "w") as output:
        output.write(str(character_list))
    index = index + 1

上面的代码是我为了让完整列表显示在文本文档中而编写的,但它只是将所有内容放在一行中。

我需要这样设置:

神奇女侠

戴安娜王子

小时 5 5 0 0 90

蝙蝠侠

布鲁斯·韦恩

h 6 2 0 4 80

代替:

[['Wonder Woman', 'Diana Prince', 'h', 5, 5, 0, 0, 90], ['Batman', 'Bruce Wayne', 'h', 6, 2, 0, 4, 80],

这是上面发布的代码的输出。

而且代码必须在循环中!

【问题讨论】:

  • 您每次都打开文件并从头开始用整个列表重写它,次数与元素数量一样多
  • SO 不是免费的教程网站。您发布了代码,但没有说明哪个部分有问题或令人困惑。
  • 欢迎来到 Stack Overflow。您是否尝试诊断问题?例如,您究竟希望str(character_list) 做什么?用您自己的话来说,您认为解决问题的合乎逻辑的步骤是什么?当您获得列表时,您应该写入文件的第一件事是什么?第二? ETC。?该列表是否有一些特别有趣的内部结构?
  • 好吧,我忘了提。此列表在列表中。因此,例如 character_list[0][0] 将是神奇女侠。我对 python 很陌生,我不确定如何组合功能,例如获取名称然后创建一个新行。
  • 如果你做for character in character_list:,那么character[0]是第一个元素,character[1]是第二个元素,以此类推。三个打印语句,你就完成了。

标签: python python-3.x list txt


【解决方案1】:

试试这个。

def write_to_file(filename, character_list):
    ### Using a while loop to iterate over the list of lists (characters).
    index = 0
    while index < len(character_list):
        with open("new_characters.txt", "w") as output:
            for item in character_list:
                for character in item:
                    output.write(str(character) + '\n')
        index = index + 1

【讨论】:

  • 不幸的是不起作用。在同一行打印
  • 不需要while index...循环
  • @Jayden。我编辑了我的代码。
【解决方案2】:

这适用于您以您要求的格式显示的子集。

def write_to_file(filename, character_list):

    # open file with given filename, in 'write' mode
    with open(filename, 'w') as f:

        # iterate over characters in for loop
        # using tuple unpacking
        for (hero_name, char_name, *data) in character_list:

            # write hero and character names on a line each
            f.write(hero_name + '\n') # e.g. 'Wonder Woman'
            f.write(char_name + '\n') # e.g. 'Diana Prince'

            # convert all remaining elements to a string
            # using list comprehension
            data = [str(i) for i in data]

            # create a single string from a list of values separated by a space
            # using string join method on the list
            data = ' '.join(data)

            # write to file with newline
            f.write(data + '\n') # e.g. 'h 5 5 0 0 90'

其中的关键组件是tuple unpackinglist comprehensionsstring join method。我还包括了在打开文件时实际使用的文件名参数的使用。这意味着您必须将带有扩展名的文件名传递给函数调用,如果您还没有这样做的话。

【讨论】:

    【解决方案3】:

    试试这个方法:-

    • For 循环会是更好的选择
    • 使用\n 换行
    def write_to_file(filename, character_list):
        with open(f"{filename}.txt", "w") as output:
            for characters in character_list:
                for character in characters:
                    character =str(character)
                    output.write(character+("\n" if len(character)>1 else "" ))
                    #output.write(character+("\n" if len(character)>1 else " " )) for  --> h 5 5 0 0 9 0
    
    write_to_file('Any',[['Wonder Woman', 'Diana Prince', 'h', 5, 5, 0, 0, 90], ['Batman', 'Bruce Wayne', 'h', 6, 2, 0, 4, 80]])
    

    输出:

    Wonder Woman
    Diana Prince
    h550090
    Batman
    Bruce Wayne
    h620480
    

    【讨论】:

    • 你试过运行这个吗?
    • @Mad Physicist 我的错。我现在已经更正了。
    • 不,你没有。
    猜你喜欢
    • 2014-08-31
    • 2020-04-20
    • 1970-01-01
    • 2014-12-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-22
    • 1970-01-01
    • 2016-03-17
    相关资源
    最近更新 更多