File handling in Python

                                                        File handling in Python

  • File handling in Python allows you to work with files on your computer's storage. You can open files, read data from them, write data to them, and close them when you're done. 
  • This is useful for tasks like reading text files, writing logs, or processing data stored in files.


  • "r": Open for reading (default). Raises FileNotFoundError if the file doesn't exist.
  • "w": Open for writing. Creates a new file if it doesn't exist, overwrites the existing content if it does.
  • "a": Open for appending. Creates a new file if it doesn't exist. Writes to the end of the file if it does.
  • "b": Binary mode. Appends "b" to other modes (e.g., "rb", "wb") to indicate binary mode.

  • "+": Open for updating (reading and writing).

    Reading from Files: You can read from a file using methods like read(), readline(), or readlines().

  • read(): Reads the entire content of the file as a single string.
  • readline(): Reads a single line from the file.
  • readlines(): Reads all lines from the file and returns them as a list.

    Writing to Files: You can write to a file using the write() method.

  • Program Syntax:


  • open("filename.txt", "mode"): This function opens a file named "filename.txt" in the specified mode. Modes include "r" for reading, "w" for writing (creates a new file or overwrites existing content), "a" for appending (adds content to the end of the file).
  • file.read(): Reads the entire content of the file as a string.
  • file.write("Hello, world!"): Writes the string "Hello, world!" to the file.
  • file.close(): Closes the file after you're done working with it. It's important to close files after using them to free up system resources and ensure data integrity.
  • Example program:











Comments

Popular posts from this blog

Unveiling Python's Mystique

PYTHON THEORY BASED INTERVIEW QUESTIONS

Exploring Essential Python Libraries for Beginners