File handling is a fundamental aspect of programming, allowing us to read and write data to and from files.
Opening and Closing Files
Before performing any file operation, we need to open the file. Python provides the open()
function for this purpose. The open()
function takes two arguments: the filename and the mode in which the file should be opened. The mode can be specified as "r"
for reading, "w"
for writing, or "a"
for appending to an existing file.
file_read = open("example.txt", "r") # Read mode
file_write = open("example.txt", "w") # Write mode
file_append = open("example.txt", "a") # Append mode
file_binary = open("example.bin", "rb") # Binary read mode
file_text = open("example.txt", "rt") # Text read mode
file_update = open("example.txt", "r+") # Read and update mode
file.close() # Close the file
Using with
keyword. When we use this keyword we do not need to explicitly close our .file
with open("example.txt", "r") as file:
content = file.read()
print(content)
Reading from Files
Python offers different methods for reading data from files.
1. Reading the Entire File
To read the entire contents of a file, we can use the read()
method. It reads the entire file content as a string.
'''First create example.txt'''
file = open("example.txt", "r")
content = file.read()
print(content)
file.close()
2. Reading Line by Line
To read a file line by line, we can use a for
loop. Each line can be accessed as a string.
file = open("example.txt", "r")
for line in file:
print(line)
file.close()
3. Reading a Specific Number of Characters
If we want to read a specific number of characters from a file, we can use the read(n)
method, where n
represents the number of characters to be read.
file = open("example.txt", "r")
content = file.read(10) # Read first 10 characters
print(content)
file.close()
Writing to Files
Python provides several methods for writing data to files. Let's explore some of the common approaches:
1. Writing to an Empty File
To write data to a file, open the file in write mode ("w"
) or append mode ("a"
) and use the write()
method.
file = open("example.txt", "w")
file.write("Hello, World!")
file.close()
'''
Output open example.txt:
-------------------------
Hello, World!
'''
This code creates a new file called "example.txt" and writes the text "Hello, World!" to
it. If the file already exists, it will be overwritten.
2. Appending to an Existing File
If we want to add content to an existing file without overwriting the existing data, we can open the file in append mode ("a"
) and use the write()
method.
file = open("example.txt", "a")
file.write("This is an appended line.")
file.close()
'''
Output : open example.txt
-------------------------
Hello, World!
This is an appended line.
'''