Reputation: 4500
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
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
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
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