Python File Handling
Python File Handling
Python provides a built-in way to handle files using the open()
function. File handling is an essential part of programming that involves reading, writing, creating, and managing files. Let's dive into the details.
Modes in File Handling
The open()
function opens a file and allows operations on it. It requires two parameters:
- File Name: The name of the file to open.
- Mode: Specifies what you want to do with the file (read, write, etc.).
Common Modes:
Mode | Description |
---|---|
'r' |
Opens a file for reading. The file must exist. |
'w' |
Opens a file for writing. Creates the file if it does not exist or overwrites if it does. |
'a' |
Opens a file for appending. Data is added at the end of the file. |
'x' |
Creates a new file. Fails if the file already exists. |
'b' |
Binary mode. Used with other modes, e.g., 'rb' for reading binary files. |
't' |
Text mode (default). Used for plain text files. |
'+' |
Opens a file for both reading and writing. |
Opening and Closing Files
# Open a file file = open("example.txt", "r") # Opens in read mode # Perform file operations... # Close the file file.close()
Using the close()
method ensures that the file is properly closed, releasing resources.
Using the with
Statement
The with
statement automatically closes the file after its block of code is executed.
with open("example.txt", "r") as file: content = file.read() print(content) # File is automatically closed after this block
Reading Files
Python provides multiple methods to read files:
-
read()
: Reads the entire file content.with open("example.txt", "r") as file: content = file.read() print(content)
-
readline()
: Reads one line at a time.with open("example.txt", "r") as file: line = file.readline() print(line)
-
readlines()
: Reads all lines and returns them as a list.with open("example.txt", "r") as file: lines = file.readlines() print(lines)
Writing Files
To write content to a file, use the 'w'
or 'a'
mode:
-
Write with
'w'
:with open("example.txt", "w") as file: file.write("Hello, World!\n") file.write("This is a new file.")
-
Append with
'a'
:with open("example.txt", "a") as file: file.write("\nAppending a new line.")
File Operations
-
Check if a File Exists:
import os if os.path.exists("example.txt"): print("File exists.") else: print("File does not exist.")
-
Delete a File:
import os if os.path.exists("example.txt"): os.remove("example.txt") print("File deleted.")
-
Create a New File:
with open("new_file.txt", "x") as file: print("New file created.")
Example: Reading and Writing
# Writing to a file with open("example.txt", "w") as file: file.write("Python File Handling Example\n") file.write("This is a sample text.\n") # Reading the file with open("example.txt", "r") as file: for line in file: print(line.strip()) # Print each line without extra spaces
Summary
Python's file handling capabilities are powerful and easy to use. With modes to control reading, writing, and appending, and features like the with
statement for automatic cleanup, Python makes working with files straightforward and efficient.