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

时间:2011-08-21 13:59:32

标签: python python-3.x

我正在尝试使用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-list类型错误;我一直在想我需要告诉定义它是否正在传递一个列表/数组,而只是声明“test”将是一个字符串。)一旦我将其更改为文本和将myfile.write与join结合使用,并将附加的\ n放入文件末尾的最后一行。

2 个答案:

答案 0 :(得分:34)

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

或者,对于一个列表,摆脱*并做我上面做的事。

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

答案 1 :(得分:2)

那里有很多错误。

  1. 你的缩进搞砸了。
  2. save_to_file中的'text'属性是指所有参数,而不仅仅是特定的参数。
  3. 您正在使用“文字模式”,这也令人困惑。请改用二进制模式,以便为'\ n'确定一致且明确的含义。
  4. 当你迭代'文本中的行'时,由于这些错误,你真正在做的是在函数中迭代你的参数,因为'text'代表你所有的参数。这就是'*'的作用。 (至少,在这种情况下。严格来说,它会迭代所有剩余的论点 - 请阅读文档)。