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 writing and reading operations to and from a file. To enable the reading and writing of files programming languages provide File I/O libraries with inbuilt methods that allow the creation, updation as well as reading of 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 open(filepath, mode) is 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)Python
- 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.
Reading files in Python
Method 1: Read a Text file In Python using read()
Method 2: Read a Text file In Python using readlines()
The file is opened using the open() method in reading r mode. The data read from the file is printed to the output screen using readlines() function. The file opened is closed using the close() method.
Writing files in Python
Method 1: Write in a Text file In Python using write()
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 with the help of write(). The with block ensures that once the entire block is executed the file is closed automatically.
File written successfully
Here is the text file gfg.txt created:
Method 2: write in a Text file In Python using writelines()
The file is opened with the open() method in w mode within the with block, the argument will write text to an existing text file with the help of readlines(). The with block ensures that once the entire block is executed the file is closed automatically.
Below is the text file gfg.txt: