0

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?

data_person
  • 4,194
  • 7
  • 40
  • 75

3 Answers3

2

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...

mrCarnivore
  • 4,638
  • 2
  • 12
  • 29
0

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.

O.Suleiman
  • 898
  • 1
  • 6
  • 11
0

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

Omi Harjani
  • 737
  • 1
  • 8
  • 20