17. Python File Handling
Python File Handling
File handling is an essential part of any web application or data processing script. Python provides built-in methods to create, read, update, and delete files.
Working with files involves two main steps: opening the file, and then performing an operation (reading or writing). It is also critical to close the file when you are done to free up system resources.
The open() Function
The key function for working with files in Python is the open() function. The open() function takes two parameters: filename, and mode.
There are four different methods (modes) for opening a file:
- "r" - Read: Default value. Opens a file for reading, error if the file does not exist.
- "a" - Append: Opens a file for appending, creates the file if it does not exist.
- "w" - Write: Opens a file for writing, overwrites existing data, creates the file if it does not exist.
- "x" - Create: Creates the specified file, returns an error if the file exists.
Reading a File
To read a file, pass the name of the file to the open() function. The file object has a read() method for reading the content of the file.
The 'with' Statement
A better and more Pythonic way to open a file is by using the with statement. This ensures that the file is properly closed after its suite finishes, even if an exception is raised along the way.
Reading Lines
You can return one line by using the readline() method. By calling it twice, you read the first two lines.
To loop through the lines of the file, you can easily loop over the file object itself. This is highly memory-efficient for reading massive files.
Writing to an Existing File
To write to an existing file, you must add a parameter to the open() function: "a" for append, or "w" for write (overwrite).
Creating a New File
To create a new file in Python, use the open() method, with one of the following parameters: "x", "a", or "w".
Deleting a File
To delete a file, you must import the OS module, and run its os.remove() function. Attempting to remove a file that does not exist will cause an error.
Knowledge Check
Ready to test your understanding of 17. Python File Handling?