How to write data from list to a file in Python?

in my previous article we have seen how to read the content of a text file to a list variable. In this article we will see how to write date from list to a file. There are several ways to write the content of a list variable to a file. The easiest way is to open the file in write mode using the open() built-in function and write the file using writelines() function. Here is an example.

file_content_list = ['First sentence.', 
    'Second sentence.', 
    'Third sentence.'] 
try:
    with open('app1.log', 'w', encoding = 'utf-8') as file:
        file.writelines(file_content_list)

except IOError as e:
    print("Unable to work on file. %s" % e)
    exit(1)
except:
    print("Unexpected error:", sys.exc_info())
    exit(1)

In the above example, every element in the list will be written to the file in a continuous manner without any line break. If you want to write every list element in separate lines then add a line of code to append \n to every item in the list before writing the list to the file.

Here is the line of code to append line break to all the list elements:

file_content_list = [element + "\n" for element in file_content_list]

Example to write data from list with line break for each element

Now we will add the line break technique to our sample code.

file_content_list = ['First sentence.', 
    'Second sentence.', 
    'Third sentence.'] 

file_content_list = [element + "\n" for element in file_content_list]

try:
    with open('app1.log', 'w', encoding = 'utf-8') as file:
        file.writelines(file_content_list)

except IOError as e:
    print("Unable to work on file. %s" % e)
    exit(1)
except:
    print("Unexpected error:", sys.exc_info())
    exit(1)
write data from list to a file in Python

Reference

  • More about the in-built open() function at Python docs.


Leave your thoughts...

This site uses Akismet to reduce spam. Learn how your comment data is processed.