File Handling

File Handling Basics

  • File handling in programming allows you to create, read, update, and delete files on your computer.
  • Files can hold various types of data such as text, images, audios, videos, etc.
  • File handling is necessary when you want to store data permanently or exchange data between different programs.
  • Most programming languages provide built-in support for file handling.

Opening and Closing Files

  • Before reading from or writing to a file, you must first open the file.
  • You can open a file in different modes, such as read mode (r), write mode (w), and append mode (a).
  • In write mode, if the file does not exist, it will be created. If it does exist, the existing content will be deleted before the new write operation.
  • In append mode, new data will be added at the end of the file, not erasing the existing data.
  • Once you’re done with a file, you should close it. This frees up the resources that were tied with the file and is done using the close() function.

Reading from a File

  • When a file is opened in read mode, you can use the read() function to read the file’s content.
  • Often, files are read line by line using a loop and the function readline().
  • Always ensure that the file exists before attempting to open and read it. Otherwise, the program might crash.

Writing to a File

  • When a file is opened in write or append mode, you can write data to the file using the write() function.
  • Using a loop, you can write multiple lines of data to a file.
  • Remember, in write mode, the existing content of the file is deleted before new data is written.

File Paths

  • When opening a file, you need to provide the file path, which tells your program where the file is located on your computer.
  • A relative file path specifies the file’s location in relation to the current folder, while an absolute file path specifies the file’s exact location on the computer.

Error Handling with Files

  • It’s important to use error handling techniques when performing file operations to prevent your program from crashing if something unexpected happens (like trying to open a file that doesn’t exist).
  • For example, a try/except block can be used to catch and handle exceptions that are raised when attempting to perform file operations.

Binary Files

  • When working with text, you usually open the file in text mode (t), but for non-text files like images or executables, you open the file in binary mode (b).
  • Binary mode doesn’t translate the file in any way and the contents are read and written as they are.