File Handling

File handling in Python allows you to read from and write to files on your computer. This functionality is essential for processing and storing data, enabling you to interact with external files seamlessly. This tutorial provides an overview of file handling in Python, covering file opening, reading, writing, and closing operations.

Opening a File

To open a file in Python, you can use the built-in open() function. This function takes two arguments: the file path and the mode in which you want to open the file (e.g., read, write, append).


      # Opening a file in read mode
      file = open("data.txt", 'r')
      

Reading from a File

Once a file is opened in read mode, you can read its contents using various methods.

Reading the Entire File


      # Reading the entire file as a single string
      content = file.read()
      print(content)
      

Reading Lines


      # Reading individual lines of the file into a list
      lines = file.readlines()
      for line in lines:
          print(line)
      

Writing to a File

To write to a file, you need to open it in write mode. If the file does not exist, Python will create it. If the file already exists, its contents will be overwritten.


      # Opening a file in write mode
      file = open("output.txt", 'w')

      # Writing to the file
      file.write("Hello, World!\n")
      file.write("This is a new line.")
      

Appending to a File

In append mode, you can add new content to an existing file without overwriting its current contents.


      # Opening a file in append mode
      file = open("output.txt", 'a')

      # Appending to the file
      file.write("\nThis line is appended.")
      

Closing a File

After you are done reading from or writing to a file, it is essential to close it using the close() method.


      # Closing the file
      file.close()
      

Using with Statement

To ensure that files are automatically closed after use, you can use the with statement. It automatically handles the opening and closing of files.


      # Using the with statement to open and automatically close the file
      with open("data.txt", "r") as file:
          content = file.read()
          print(content)