File Handling in Python
What is File Handling? File handling means working with files to save or read data. In Python, you can open files, write to them, read from them, and close them easily. It is useful for storing and managing information, like saving a list of names or reading a saved report.
1. Opening a File
Before we can work with a file (like reading its content or writing something into it), we must open it. Python
provides an easy way to do this using the open() function.
The open() function needs two things:
- The name of the file you want to work with.
- The mode, which tells Python how you want to open the file.
Common Modes in open():
- 'r' (Read): Opens the file for reading. This is the default mode. You can only look at the file's content, not change it.
- 'w' (Write): Opens the file for writing. It erases all existing content if the file already exists. If the file doesn’t exist, it creates a new one.
- 'a' (Append): Opens the file to add (append) new content at the end without deleting anything. If the file doesn’t exist, it creates a new one.
- 'x' (Exclusive Creation): Creates a new file but gives an error if the file already exists.
Example 1: Open a File in Read Mode
Let’s say we have a file named example.txt that contains some text. We want to open it and read its
content:
# Example: Open and Read a File
file = open("example.txt", "r") # Open the file in 'r' (read) mode
content = file.read() # Read the entire content of the file
print(content) # Display the content on the screen
file.close() # Close the file after use
Output:
If example.txt contains:
Hello, this is a sample file. Welcome to Python file handling!
The program will display:
Hello, this is a sample file. Welcome to Python file handling!
Step-by-Step Explanation:
-
file = open("example.txt", "r"): This opens the file namedexample.txtin read mode ('r'). If the file doesn’t exist, Python will show an error. -
content = file.read(): Theread()method reads all the text inside the file and stores it in the variablecontent. -
print(content): This displays the file’s content on the screen. -
file.close(): After finishing, always close the file usingclose(). This frees up resources and prevents errors.
Important Notes:
- If the file does not exist and you try to open it in
'r'mode, Python will throw aFileNotFoundError. - Always close the file after using it to avoid problems like memory leaks.
Example 2: What Happens if the File Doesn’t Exist?
Let’s try to open a file that does not exist:
# Trying to open a non-existent file
file = open("nonexistent.txt", "r") # This file does not exist
content = file.read()
print(content)
file.close()
This will give an error:
FileNotFoundError: [Errno 2] No such file or directory: 'nonexistent.txt'
How to Handle Such Errors:
We can avoid this error by using a try and except block:
# Handle error if file doesn't exist
try:
file = open("nonexistent.txt", "r") # Trying to open a non-existent file
content = file.read()
print(content)
file.close()
except FileNotFoundError:
print("The file does not exist. Please check the file name.")
Output:
Instead of crashing, the program will display:
The file does not exist. Please check the file name.
Example 3: Use the with Statement
A better way to open files is by using the with statement. This ensures the file is automatically
closed after its use:
# Using 'with' to open a file
with open("example.txt", "r") as file:
content = file.read() # Read the file
print(content) # Print the content
# No need to call file.close(); it’s done automatically
Using with is safer and more efficient because Python handles closing the file for you.
2. Reading from a File
Python provides multiple ways to read data:
read(): Reads all content at once.readline(): Reads one line at a time.readlines(): Reads all lines and returns them as a list.
Example: Read File Line by Line
# Read a file line by line
file = open("example.txt", "r")
for line in file: # Loop through each line
print(line.strip()) # Print each line without extra spaces
file.close()
Explanation: The for loop goes through each line in the file. strip()
removes unnecessary spaces.
3. Writing to a File
To write new data to a file, we use the write() method. However, be careful when using
'w' mode, because it will erase everything already in the file and replace it with the new content
you write.
Example 1: Write to a File
Let’s say we want to create a file or overwrite an existing file, and then write some new content into it. Here’s how you do it:
# Example: Write new data to a file
file = open("example.txt", "w") # 'w' mode opens the file for writing (it overwrites the file if it exists)
file.write("Hello, Python learners!\n") # Write a line of text
file.write("File handling is easy to learn.") # Write another line of text
file.close() # Always close the file when done
Output in the file:
Hello, Python learners! File handling is easy to learn.
Explanation:
- We opened the file
example.txtin'w'mode, which means we are writing to it. If the file already exists, it will be completely replaced with the new content. write()writes the text provided to the file. In this case, we wrote two lines.close()ensures the file is properly closed after writing, which is important to save the changes and free up system resources.
Important Points about Writing:
- If the file
example.txtdoesn’t exist, Python will create it automatically. - If you open a file in
'w'mode and the file already has content, it will be erased, and the new content will be written instead. So, be careful not to lose important data.
4. Appending to a File
If you want to add new data to the end of an existing file without removing the current content, you can use
'a' mode. This is called appending.
Example 2: Append to a File
Now, let’s say we want to add some more content to example.txt without losing the existing text.
Here's how you do it:
# Example: Add more data to an existing file
file = open("example.txt", "a") # 'a' mode opens the file for appending (doesn't erase existing content)
file.write("\nThis line is added to the file.") # Append a new line of text
file.close() # Always close the file when done
Output in the file:
Hello, Python learners! File handling is easy to learn. This line is added to the file.
Explanation:
- We opened the file
example.txtin'a'mode. This mode allows us to add content without touching the existing content. - The
write()method appends the new line at the end of the file. close()is used to safely close the file after appending the text.
Important Points about Appending:
- If the file doesn’t exist,
'a'mode will create the file and then add the new content. - Unlike
'w'mode,'a'doesn’t delete anything from the file; it simply adds new data at the end.
Summary:
- Use 'w' mode to overwrite a file and write new content. Be careful, as it will erase any previous
data in the file.
- Use 'a' mode if you want to add new content to an existing file without removing anything.
5. Handling Errors
What if the file doesn’t exist? Or you don’t have permission to open it? Python allows you to handle such errors
using try and except.
Example: Handle Missing File Error
# Handle file errors
try:
file = open("missing_file.txt", "r") # This file doesn't exist
print(file.read())
file.close()
except FileNotFoundError:
print("The file does not exist. Please check the filename.")
Explanation: The try block attempts to open a file. If the file is not found, the
except block runs, displaying an error message.
6. Closing a File
Always close a file after using it with the close() method. This frees up system resources.
Better Way to Work with Files
Use the with statement to automatically close files:
# Automatically close file
with open("example.txt", "r") as file:
content = file.read()
print(content)
Explanation: The with block automatically closes the file when done. It’s safer
and easier to use.
Summary of Key Points:
- Use
'w'to overwrite a file. - Use
'a'to add new content to a file. - Always close a file after use or use the
withstatement for automatic closure. - Handle file-related errors using
tryandexceptto prevent crashes.