6 Methods to write a list to text File in Python

In this post, We are going to learn 6 Methods to write a list to text File in Python, we have a built-in method for writing a file. While programming we have to write a lot of data to be stored in the computer except the data structure list object in memory to perform a further operation or store it for later use.

How to create a file in Python


Using open() method

it takes two arguments, The first is the file name, and the second represents the mode(permission) of the file. To create a file in python, we use the following syntax.

Syntax

file = open("File_Name", "Access_Mode")

The name of the file is ‘devenum.txt’, and ‘w’ represents that we want to create a new file if it does not exist, Also that has permission to write.

Steps to create a text file


  • Open the file using the open() method in write mode using ‘w’. The point to note here is that the ‘w’ specifier creates a new file, if the file does not exist else overwrite the existing file.
  • Write to file using write() method
  • Close a file using a close() method.

1.Program example: Create a file object and write data

list_file = open("devenum.txt","w")
list_file.write('my first file!\n')
list_file.close()

2.open() method with Statement

The above code of writing file can be simplified with lesser code using with a statement

with open('devenum.txt', 'w') as file_list:
    file_list.write('my firt file\n')

To write a Python list into a file in we have these methods

  • Single line method
    • Write()
  • Multiline method
    • writelines()
  • JSON module
  • Using unpack operator
  • Using NumPy.savetxt() method

1. Write() method to Write a list line by line


To write a list into a file line by line we will use the write () method. We are creating a file in write mode and loop over the element of the list one by one as well to write them in the file. In this line my_list_file.write(‘%s\n’ % element) we are terminating each line by a special character that is EOF(end of file) or newline (\n) or line break.

#list of programming langauges
lang_lst = ['C#','Pyhthon','Go','Data','C#','16','17','35','68']

with open('devenum.txt', 'w') as my_list_file:

   #looping over the each ist element

    for element in lang_lst:

         #writing to file line by line

        my_list_file.write('%s\n' % element)

Created file “devenum.txt” content is shown in the output

Output

C#
Pyhthon
Go
Data
C#
16
17
35
68

2. Using join() and write() method to write list to file


In this example, we join all the lists using the join() method and then writing all the list elements in one go. In this way, we don’t need to loop over each item on the list.

#list of programming langauges
lang_lst = ['C#','Python','Go','Data','C#','16','17','35','68']

with open('devenum.txt', 'w') as my_list_file:
      file_content = "\n".join(lang_lst)

      my_list_file.write(file_content)

Output

C#
Python
Go
Data
C#
16
17
35
68

3. Write entire list using writelines() method


the writelines() is a multiline method() that we often use to write an entire list into a file in one go. Let us understand with an example of how we can do this.

writelines() using looping over each element

We are looping over the elements of list in writelines() and writing line by line.

#defining a list
lang_lst = ['C#','Python','Go','Data','C#','16','17','35','68']

with open('devenum.txt', 'w') as my_list_file:
    
  my_list_file.writelines("%s\n" % lang for lang in lang_lst)

The content of created file “devenum.txt” is shown in the output

Output

C#
Python
Go
Data
C#
16
17
35
68

writeline() to write a list object in file

We can pass the list directly using the writeline() method.

#list of programming langauges
lang_lst = ['C#','Python','Go','Data','C#','16','17','35','68']

with open('devenum.txt', 'w') as my_list_file:
    
  my_list_file.writelines("%s\n" % lang_lst)
    

Created file “devenum.txt” content is shown in the output

Output

['C#', 'Python', 'Go', 'Data', 'C#', '16', '17', '35', '68']

4. Write a list into file using JSON


Another way to write the list file in JSON format in the text file using the JSON Module. We dump the list using the JSON module DUMP() method. The process is the same as we have seen in the above example. More we can understand with an example.

import json
#list of programming langauges
lang_lst = ['C#','Pyhthon','Go','Data','C#','16','17','35','68']

with open('devenum.txt', 'w') as my_list_file:
  json.dump(lang_lst, my_list_file)
     

The output will be as shown below in devenum.txt file.

Output

["C#", "Pyhthon", "Go", "Data", "C#", "16", "17", "35", "68"]

5. unpack operator with print() method


The unpack operator(*) unpack an iterable(list,dictionary,tuple).We can use it with print() method to convert list to a file.

import pickle

#list of programming langauges
lang_lst = ['C#','Pyhthon','Go','Data','C#','16','17','35','68']

with open('devenum.txt', 'w') as my_list_file:
  print(*lang_lst,sep="\n",file= my_list_file)


6.NumPy savetxt() method to write a list to text file


we can use Numpy.savetxt() method converts an array or list to a text file. The frm argument use to specifying the format of the file and delimiter parameter for a set delimiter.

We don’t need to open files using Numpy.savetxt() method.

import numpy as np

#list of programming langauges
lang_lst = ['C#','Pyhthon','Go','Data','C#','16','17','35','68']


np.savetxt('devenum.txt',lang_lst,delimiter="\n", fmt="%s")


Conclusion:

We have explored 4 Methods to write a list to text File that includes single-line multi-line and JSON.