简体   繁体   English

如何将列表的每个元素写入文本文件的每一行?

[英]How can I write each element of a list to each line of a text file?

Using python, I've got the following list: 使用python,我得到以下列表:

data = ['element0', 'element1', 'element2', 'element3']

And I want to write each element, into a new line of "myfile.txt", so I've been trying this: 而且我想将每个元素写入“ myfile.txt”的新行中,因此我一直在尝试:

for x in data:
    open("myfile.txt", "w").write(x + "\n")

Which gives me this (inside "myfile.txt"): 这给了我这个(在“ myfile.txt”内部):

element3

I looks like each time it goes through the loop, it writes the element on top of the last. 我看起来每次循环都将元素写在最后一个元素的顶部。

Desired result (inside "myfile.txt"): 所需的结果(在“ myfile.txt”内部):

element0
element1
element2
element3

Just open the file object once : 只需打开文件对象一次

with open("myfile.txt", "w") as fobj:
    for x in data:
        fobj.write(x + "\n")

I'm using the file as a context manager by passing it to the with statement; 通过将文件传递给with语句,我将该文件用作上下文管理器 this ensures that the file is closed again after the block of code finishes. 这样可以确保在代码块完成之后再次关闭文件。

Each time you open the file object with the 'w' (write) mode, the file is truncated , emptied out. 每次以'w' (写入)模式打开文件对象时,文件都会被截断 ,清空。 You'd have to use the 'a' (append) mode to prevent the file being truncated. 您必须使用'a' (附加)模式来防止文件被截断。

However, opening the file just once is much more efficient. 但是,只打开一次文件效率更高。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM