file handling

In Python, file handling refers to reading and writing data to files. Here are some common operations and functions related to file handling in Python:

  1. Opening a File: To open a file, you can use the open() function and specify the file name and mode (read, write, append, etc.).
    • file = open("myfile.txt", "r")
    • # Opens the file in read mode
  2. Reading from a File: Once a file is opened, you can read its contents using methods like read(), readline(), or readlines().pythonCopy code
    • content = file.read() # Reads the entire file content
    • line = file.readline() # Reads a single line from the file
    • lines = file.readlines() # Reads all lines and returns a list
  3. Writing to a File: To write data to a file, you need to open it in write mode ("w") or append mode ("a"), and then use the write() method.
    • file = open("myfile.txt", "w") # Opens the file in write mode file.write("Hello, World!") # Writes data to the file
    • file.close() # Closes the file
  4. Appending to a File: If you want to add content to an existing file without overwriting its contents, open the file in append mode ("a") and use the write() method.
    • file = open("myfile.txt", "a") # Opens the file in append mode file.write("New content") # Appends data to the file
    • file.close() # Closes the file
  5. Closing a File: It’s important to close the file after you’re done with it to release system resources.
    • file.close()
    • # Closes the file
  6. Using Context Managers (Recommended): A better practice is to use the with statement, which automatically closes the file after the block of code.
    • with open("myfile.txt", "r") as file:
    • content = file.read()
    • # File is automatically closed outside the 'with' block
  7. Error Handling: When working with files, errors can occur. To handle exceptions, you can use try and except blocks.
    • try:
    • file = open(“myfile.txt”, “r”)
    • # Perform file operations
    • except FileNotFoundError:
    • print(“File not found!”)
    • finally:
    • file.close() # Close the file regardless of an exception

These are some of the fundamental file handling operations in Python. It’s important to handle file operations properly, close files after use, and handle potential exceptions to ensure clean and error-free file handling.

Leave a comment