简体   繁体   中英

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

Using python, I've got the following list:

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:

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

Which gives me this (inside "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"):

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; 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. You'd have to use the 'a' (append) mode to prevent the file being truncated.

However, opening the file just once is much more efficient.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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