Skip to content
Related Articles

Related Articles

Reading and Writing lists to a file in Python
  • Last Updated : 11 Dec, 2020

Reading and writing files is an important functionality in every programming language. Almost every application involves write and read operations to and from a file. To enable reading and writing of files programming languages provide File I/O libraries with inbuilt methods that allow the creation, updation as well as reading data from the files. Python is no exception. Python too offers inbuilt methods to perform file operations. The io module in Python is used for file handling. The following examples demonstrate reading and writing lists to a file in Python.

The methods involved are:

open(filepath, mode): Used to open the required file in the desired mode. The open() method supports various modes of which three are of main concern:

  • r:  read (default)
  • w: write
  • a: append

write(): Inserts the string str1 in a single line in the text file.

read(): used to read data from the file opened using the open() method. 



Below are various examples depicting Reading and Writing lists to a file in Python:

Example 1:

The file is opened with the open() method in w+ mode within the with block, the w+ argument will create a new text file in write mode. The with block ensures that once the entire block is executed the file is closed automatically. 

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# assign list
l = ['Geeks','for','Geeks!']
  
# open file
with open('gfg.txt', 'w+') as f:
      
    # write elements of list
    for items in l:
        f.write('%s\n' %items)
      
    print("File written successfully")
  
  
# close the file
f.close()

chevron_right


Output:

Here is the text file gfg.txt created:



Reading list from the file, the file that was written in the example above is read in this example. The file is opened using the open() method in read r mode. The data read from the file is printed to the output screen. The file opened is closed using the close() method.

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# open file in read mode
f = open('gfg.txt', 'r')
  
# display content of the file
print(f.read())
  
# close the file
f.close()

chevron_right


Output:

Example 2:

The file is opened with the open() method in a mode within the with block, the a argument will append text to an existing text file. The with block ensures that once the entire block is executed the file is closed automatically.

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# assign list
l = ['Geeks', '4', 'geeks']
  
# open file
with open('gfg.txt', 'a') as f:
  
    # write elements of list
    for items in l:
        f.write('%s\n' % items)
  
    print("File appended successfully")
  
# close the file
f.close()

chevron_right


Output:

Below is the text file gfg.txt:

Now reading the text file

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# open file in read mode
f = open('gfg.txt', 'r')
  
# display content of the file
for x in f.readlines():
    print(x, end='')
  
# close the file
f.close()

chevron_right


Output:

The main difference between read() and readLines() is read() reads the entire content of the file all at once whereas readlines() reads each line at a time. With read() we can also specify the number of characters to be read. The readlines() method returns each line of the file as list of strings. 

Implementation:

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# open file form two file objects
f1 = open('gfg.txt', 'r')
f2 = open('gfg.txt', 'r')
  
# display content of the file
print("\nOutput from readlines():")
print(f1.readlines())
  
print("\nOutput from read():")
print(f2.read())
  
# close the files
f1.close()
f2.close()

chevron_right


Output:


Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :