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?

7
  • 4
    print(test_list) shows what? Commented Jan 30, 2018 at 12:34
  • What is test_list? Commented Jan 30, 2018 at 12:34
  • 3
    Are you sure that len(test_list) > 0? Commented Jan 30, 2018 at 12:34
  • I have updated the test_list. It is just a list of strings. Commented Jan 30, 2018 at 12:36
  • 1
    Your code works. Maybe you are lookin in the wrong directory? Commented Jan 30, 2018 at 12:38

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.