File Handling in Python

File handling in Python is a fundamental skill that allows you to interact with external files on your computer. Reading from and writing to files is essential for various data processing tasks and for working with external resources, such as databases or configuration files.

Reading from Files:

        
            # Example of reading from a text file
            with open('example.txt', 'r') as file:
                content = file.read()
                print(content)
        
    

Writing to Files:

        
            # Example of writing to a text file
            with open('output.txt', 'w') as file:
                file.write('Hello, World!')
        
    

File Handling Exercise:

Exercise: Summing numbers from a file and writing the result to another file. Follow these steps to work on the exercise:

  1. Create a text file named "data.txt" in the same directory as this Python script.
  2. In the "data.txt" file, write a list of numbers (one number per line).
  3. Write a Python script to read the numbers from "data.txt" and calculate their sum.
  4. Open another file named "result.txt" in write mode and write the calculated sum into it.
  5. Run your Python script and check if "result.txt" contains the correct sum.

File handling is a powerful feature in Python that allows you to work with various file formats and external resources. Remember to always close the file using the with statement or the close() method to free up system resources after you finish reading or writing. Additionally, make sure to handle exceptions appropriately to handle potential errors during file operations.

File Handling In Python YouTube Video