File Handling In Python
File handling in Python involves working with files, reading from them, and writing to them. Python provides built-in functions and methods to perform file operations.
Example:
# Creating a file
with open("example.txt", "w") as file:
file.write("Hello, this is a sample file.\nPython is awesome!")
# Reading from a file
with open("example.txt", "r") as file:
content = file.read()
# Appending to a file
with open("example.txt", "a") as file:
file.write("\nAppending more content.")
# Reading lines from a file
with open("example.txt", "r") as file:
lines = file.readlines()
In the example above, we:
- Create a file named "example.txt" and write content to it.
- Read the entire content of the file.
- Append additional content to the file.
- Read lines from the file into a list.
File Position Methods in Python
In Python, file objects provide methods to manage the file's current position, allowing you to read and write data at specific locations within a file. Two key methods for managing file positions are seek()
and tell()
:
Example:
# Opening a file in write mode
with open("example.txt", "w") as file:
# Writing data to the file
file.write("Hello, World!")
# Getting the current file position
position_before = file.tell()
# Moving the file position to the beginning
file.seek(0)
# Reading data from the beginning
content = file.read()
# Getting the updated file position
position_after = file.tell()
In the example above, a file named "example.txt" is opened in write mode. Data is written to the file using the write()
method. The tell()
method retrieves the current file position before and after using seek()
to move the position to the beginning. Finally, the content is read from the beginning of the file.
Directory Operations
In Python, directory operations refer to working with directories (folders) on a file system. The os
module provides functions for directory-related operations.
Example:
import os
# Creating a directory
os.mkdir("example_directory")
# Checking if a directory exists
directory_exists = os.path.exists("example_directory")
# Listing files in a directory
files_in_directory = os.listdir("example_directory")
# Removing a directory
os.rmdir("example_directory")
In the example above, the os.mkdir
function creates a new directory named "example_directory." The os.path.exists
function checks if the directory exists, and os.listdir
lists the files in the directory. Finally, os.rmdir
removes the directory.