- Files in programming are named sets of information stored on long-term storage devices like hard drives.
- The open() function in Python is essential for file handling, requiring a filename and a mode to open the file.
- In read mode ("r"), a file is opened for reading and an error is returned if the file does not exist.
- Append mode ("a") opens a file for adding content to the end, returning an error if the file does not exist.
- Write mode ("w") opens a file for writing, creating it if it does not exist and overwriting it if it does.
- Create mode ("x") creates a new file and returns an error if the file already exists.
- Text mode ("t") is the default mode, opening the file in text mode, while binary mode ("b") is used for non-text files.
- The read() method reads the entire content of a file, which is then printed and the file is closed to free up resources.
- Using the with statement for file handling ensures that the file is properly closed, even if an error occurs.
- Reading a file line by line can be done using a loop with the readline() method or directly with a for loop.
- The readlines() method reads all lines of a file at once and stores them in a list for further processing.
- To write to an existing file, use append mode ("a") to add content without removing existing data, or write mode ("w") to overwrite the file.
- Creating a new file can be done using write mode ("w"), append mode ("a"), or create mode ("x"), depending on the need.
- Exception handling in Python, using try-except blocks, helps manage errors and prevent program crashes.
- The finally block allows execution of code regardless of whether an exception occurred, ensuring proper cleanup actions.