Python File Handling Introduction
Python provides several functions and methods to handle files efficiently. The key file operations include creating, opening, reading, writing, and closing files. Below are the most commonly used methods and their purposes:
open()
: Opens a file and returns a file object. It takes two arguments, the filename and the mode (such as read mode'r'
or write mode'w'
).read()
: Reads the entire content of a file and returns it as a string.readline()
: Reads one line from the file at a time.write()
: Writes a specified string to the file.close()
: Closes the file to free up resources.os.remove()
: Deletes a specified file (from theos
module).
File Modes: When opening a file, you can specify the mode:
'r'
: Read mode (default). Opens the file for reading, and the file must already exist.'w'
: Write mode. Creates a new file or overwrites the existing file.'a'
: Append mode. Opens the file for appending data, preserving the existing content.'x'
: Create mode. Creates a new file, but raises an error if the file already exists.
Example: Below is a simple example to demonstrate how to open a file in read mode and print its content:
# Simple file handling example
file = open('example.txt', 'r') # Open the file in read mode
content = file.read() # Read the file content
print(content)
file.close() # Close the file
Output
[Contents of example.txt]
Important: To run these examples, make sure that the files you are working with (like example.txt
) are saved in the same directory as your Python script. You can find your script's directory by using os.getcwd()
or placing the files in your project folder.