File Handling and I/O Operations
File Handling Basics:
1. Opening a File:
- Using the open() function to open a file for reading or writing.
- Specifying the file path and mode ("r" for reading, "w" for writing, "a" for appending, etc.).
2. Reading from a File:
- Using the .read() method to read the entire file content.
- Using .readline() to read one line at a time.
- Using .readlines() to read all lines into a list.
3. Closing a File:
- Using the .close() method to properly close the file.
- Ensuring that resources are released when the file is no longer needed.
4. Writing to a File:
- Using the .write() method to write text to a file.
- Using .writelines() to write a list of strings to a file.
Context Managers and with Statement:
1. Using with Statement:
- Using the with statement to automatically handle file closing.
- Ensuring proper resource management and error handling.
2. File Objects as Context Managers:
- File objects obtained from open() can be used as context managers.
- Simplifying file handling code with the with statement.
Reading and Writing Text Files:
1. Reading Text Files:
- Using open() with mode "r" to read text files.
- Iterating through lines using a loop.
2. Writing Text Files:
- Using open() with mode "w" to write to a text file.
- Writing multiple lines using .write() or .writelines().
3. Appending to Text Files:
- Using mode "a" to append content to an existing file.
- Adding new content without overwriting the existing data.
Working with Binary Files:
1. Reading Binary Files:
- Using mode "rb" to read binary files.
- Reading bytes and byte arrays.
2. Writing Binary Files:
- Using mode "wb" to write to binary files.
- Writing bytes or byte arrays to a file.
File Paths and Directories:
1. File Paths:
- Using relative and absolute paths to specify file locations.
- Handling slashes/backslashes based on the operating system.
2. Working with Directories:
- Using os module for working with directories.
- Listing files, creating directories, etc.
3. Working with Pathlib:
- Using the pathlib module for modern file path manipulation.
- Creating paths, joining paths, checking existence, etc.
Exception Handling and Error Management:
1. Handling File-Related Errors:
- Using try and except to handle file-related exceptions.
- Ensuring graceful handling of issues like file not found.
2. Using os.path for Validation:
- Using functions from os.path module to validate file paths.
- Checking if a file exists, checking its type, etc.
3. Handling Resource Leaks:
- Ensuring that files are properly closed even in the presence of exceptions.
- Using finally block or with statement for cleanup.
CSV and Text File Parsing:
1. Reading CSV Files:
- Using the csv module to read and parse CSV files.
- Reading rows and fields as lists or dictionaries.
2. Writing CSV Files:
- Using the csv module to write data to CSV files.
- Writing rows based on lists or dictionaries.