首页 文章

如何使用Python3中的换行符将列表写入文件

提问于
浏览
18

我正在尝试使用Python 3将数组(列表?)写入文本文件 . 目前我有:

def save_to_file(*text):

    with open('/path/to/filename.txt', mode='wt', encoding='utf-8') as myfile:
        for lines in text:
            print(lines, file = myfile)
    myfile.close

这会将类似于数组的内容直接写入文本文件,即

['element1', 'element2', 'element3']
username@machine:/path$

我要做的是创建文件

element1
element2
element3
username@machine:/path$

我尝试了不同的循环方式并追加"\n"但似乎写入是在一次操作中转储数组 . 问题类似于How to write list of strings to file, adding newlines?,但语法看起来像是Python 2?当我尝试它的修改版本时:

def save_to_file(*text):

    myfile = open('/path/to/filename.txt', mode='wt', encoding='utf-8')
    for lines in text:
        myfile.write(lines)
    myfile.close

... Python shell给出了“TypeError:必须是str,而不是list”,我认为这是因为Python2和Python 3之间的变化 . 我想让每个元素在换行符上缺少什么?

编辑:谢谢@agf和@arafangion;结合你们两个人写的内容,我想出了:

def save_to_file(text):

    with open('/path/to/filename.txt', mode='wt', encoding='utf-8') as myfile:
        myfile.write('\n'.join(text))
        myfile.write('\n')

看起来我有“* text”问题的一部分(我读过这个扩展了参数,但是直到你写了[元素]变成[[元素]]我才得到一个str-not-列表类型错误;我一直在想我需要告诉定义它是一个传递给它的列表/数组,并且只是声明“test”将是一个字符串 . )一旦我将其更改为文本并使用myfile,它就起作用了 . 用连接写,附加的\ n放在文件末尾的最后一行 .

2 回答

  • 27

    那里有很多错误 .

    • 你的缩进搞砸了 .

    • save_to_file中的'text'属性是指所有参数,而不仅仅是特定参数 .

    • 你're using 463267 , which is also confusing. Use binary mode instead, so that you have a consistent and defined meaning for ' \ n' .

    当你迭代'文本中的行'时,由于这些错误,你真正在做的是在函数中迭代你的参数,因为'text'代表你所有的参数 . 这就是'*'的作用 . (至少,在这种情况下 . 严格来说,它会迭代所有剩余的参数 - 请阅读文档) .

  • 1

    myfile.close - 摆脱使用 with 的地方 . with 自动关闭 myfile ,你必须像 close() 一样调用 close ,因为当你不使用 with 时它会做任何事情 . 你应该总是在Python 3上使用 with .

    with open('/path/to/filename.txt', mode='wt', encoding='utf-8') as myfile:
        myfile.write('\n'.join(lines))
    

    不要使用 print 写入文件 - 使用 file.write . 在这种情况下,您希望在中间写入一些带有换行符的行,这样您就可以使用 '\n'.join(lines) 连接这些行,并将直接创建的字符串写入该文件 .

    如果 lines 的元素不是字符串,请尝试:

    myfile.write('\n'.join(str(line) for line in lines))
    

    首先转换它们 .

    您的第二个版本因其他原因不起作用 . 如果你通过

    ['element1', 'element2', 'element3']
    

    def save_to_file(*text):
    

    它会成为

    [['element1', 'element2', 'element3']]
    

    因为 * 将每个参数放入一个列表中,即使你传递的内容已经是一个列表 .

    如果你想支持传递多个列表,并且仍然一个接一个地写,请执行

    def save_to_file(*text):
    
        with open('/path/to/filename.txt', mode='wt', encoding='utf-8') as myfile:
            for lines in text:
                myfile.write('\n'.join(str(line) for line in lines))
                myfile.write('\n')
    

    或者,只为一个列表,摆脱 * 并做我上面做的 .

    Edit: @Arafangion是对的,您应该只使用 b 而不是 t 来写入您的文件 . 这样,您不必担心不同平台处理换行符的不同方式 .

相关问题