Python File Handling
Python File Handling
Python offers a built-in method for file handling with 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 grants access to a file for performing operations. It requires two parameters:
- File Name: Specifies the filename to be accessed.
- Mode: Defines the intended operation on the file, such as reading or writing.
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. Appends new data to the file without altering existing content.. |
'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. |
'+' |
Allows simultaneous reading and writing of a file. |
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()
: Fetches all lines from the file and stores them in a list.with open("example.txt", "r") as file: lines = file.readlines() print(lines)
Writing Files
To save content in a file, utilize `'w'
` for overwriting or `'a'
` for appending.
-
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.