Reading and Writing lists to a file in Python
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:
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.
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.
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.
Below is the text file gfg.txt:
Now reading the text file
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.
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. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course