data_person
data_person

Reputation: 4500

Writing to a text file from python list

I am trying to create a text file and write to it from a python list.

Code:

file1 = open("test.txt","w")
test_list = ['hi', 'hello', 'welcome']
for each_ele in test_list:
    file1.write(each_ele+'\n')
file1.close()

Still the file is empty, any suggestions please?

Upvotes: 0

Views: 91

Answers (3)

O.Suleiman
O.Suleiman

Reputation: 918

I suspect you are looking at the right file, Use:

import os
os.getcwd()

to check for your working directory, your created file should be there.

Upvotes: 0

Omi Harjani
Omi Harjani

Reputation: 840

It worked for me, I believe the py file doesn't have required permission, change the owner of the file using chown user:user filename.py and try:

file1 = open("sampletest.txt","w+")

file1 = open("sampletest.txt","w+")
test_list = ['hi', 'hello', 'welcome']
for each_ele in test_list:
    file1.write(each_ele+'\n')
file1.close()

output :

hi hello welcome

Upvotes: 0

mrCarnivore
mrCarnivore

Reputation: 5078

It is recommended to use with when operating with files. This works:

test_list = ['a', 'b']
with open("test.txt","w") as file1:
    for each_ele in test_list:
        file1.write(each_ele+'\n')

Most likely test_list is empty in your case... Or you are looking in a wrong directory for the file...

Upvotes: 2

Related Questions