Iterate a list and save it in a file

4

I am trying to iterate a list and then save it to a file .txt with open/write .

lista = ['uno', 'dos', 'tres']
mi_path = "../fichero.txt"
f = open(mi_path, 'a+')

for i in lista:
    f.write(i)
    f.close()

I give the attribute a+ to re-write the file .txt and continue from the last position, the problem is that only saves me the first item in the list. When doing the for loop what I want is for you to register the 3 fields of the list that I am giving you, but only do it with the first one.

    
asked by Devp Devp 12.07.2017 в 11:59
source

2 answers

6

Only saves the first item in the list because in the first iteration of the loop, after writing the first item, you close the file.

To solve it you have to close the file once you have finished recording elements in it. Try the following:

lista = ['uno', 'dos', 'tres']
mi_path = "../fichero.txt"
f = open(mi_path, 'a+')

for i in lista:
    f.write(i)

f.close()

You can also make it a little easier by using the with definition:

lista = ['uno', 'dos', 'tres']
mi_path = "../fichero.txt"

with open(mi_path, 'a+') as f:
    for i in lista:
        f.write(i)

In this way, everything inside the with is executed for the open file. And once finished the execution within the with automatically closes the file.

    
answered by 12.07.2017 / 13:03
source
4

You have to close the file after the loop:

lista = ['uno', 'dos', 'tres']
f = open("fichero.txt", "a")

for i in lista:
    f.write(i)

f.close()
    
answered by 12.07.2017 в 12:59