How to Read and Write Files with Python
In Python, you can open, create, or add records to a text file.
Creating a New File
To create a file in Python, start by opening it in write mode using the open function with the "w" (write) parameter.
Here, f is the logical name of the file within the program, while "filename" is the actual name of the file on the computer.
f = open("filename","w")
f.write("first record \n")
f.close()
The write function writes individual records to the file. The \n character signifies the end of a record and a new line.
After writing all the records, close the file using the close function.
This saves the file to your PC.
Adding Records to an Existing File
To add records to an existing file without deleting the current content, open the file using the open function with the "a" (append) parameter.
f = open("filename","a")
f.write("second record \n")
f.write("third record \n")
f.close()
The "a" parameter stands for append, which adds new records to the file without erasing existing ones.
Now, the physical file on your computer contains three records (lines).
first record
second record
third record
Opening and Reading a File
To open a file for reading, use the open function with the "r" (read) parameter.
You can read the file's contents using two methods:
- The readline method reads one record at a time.
- The read method reads the entire content of the file at once.
Example 1 (readline)
The following code opens the file for reading using the readline method.
It then reads and prints the first three records.
f = open("filename","r")
print(f.readline())
print(f.readline())
print(f.readline())
f.close()
Example 2 (read)
This code opens the file for reading.
It then reads all the records using the read method.
f = open("filename","r")
print(f.read())
f.close()
The program output is as follows:
first record
second record
third record
Example 3 (readlines)
This code opens the file for reading.
It then reads all the records and returns them as an array.
f = open("filename","r")
print(f.readlines())
f.close()
Each element of the array is a record from the file.
['first record \n', 'second record \n', 'third record \n']
This demonstrates how to write and read a text file using Python.
Example 4
To read all the records from the file from start to finish:
f = open("filename","r")
while True:
line = f.readline()
if not line:
break
print(line)
f.close()
This script reads and prints all the records in the file.
And so on.