Reading and Writing lists to a file in Python - GeeksforGeeks

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
# assign listl = ['Geeks','for','Geeks!']  # open filewith 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 filef.close()
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
# open file in read modef = open('gfg.txt', 'r')  # display content of the fileprint(f.read())  # close the filef.close()
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
# assign listl = ['Geeks', '4', 'geeks']  # open filewith 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 filef.close()
Output:
Below is the text file gfg.txt:
Now reading the text file
Python3
# open file in read modef = open('gfg.txt', 'r')  # display content of the filefor x in f.readlines():    print(x, end='')  # close the filef.close()
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
# open file form two file objectsf1 = open('gfg.txt', 'r')f2 = open('gfg.txt', 'r')  # display content of the fileprint("\nOutput from readlines():")print(f1.readlines())  print("\nOutput from read():")print(f2.read())  # close the filesf1.close()f2.close()
Output:
Python file-handling-programs
python-file-handling
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
Check if element exists in list in Python