Python Tutorial

Python Variable

Python Operators

Python Sequence

Python String

Python Flow Control

Python Functions

Python Class and Object

Python Class Members (properties and methods)

Python Exception Handling

Python Modules

Python File Operations (I/O)

Basic operations of Python files

In Python, you can perform various file operations such as reading, writing, and appending data to files. Here is an overview of the basic operations for working with files in Python:

  • Opening a file:

To open a file, use the open() function. It takes two arguments: the file path and the mode in which you want to open the file. The mode can be 'r' for reading, 'w' for writing, 'a' for appending, and 'x' for creating a new file. If the mode is not specified, it defaults to 'r' (reading).

file = open("example.txt", "r")
  • Closing a file:

After you have finished working with a file, it is important to close it using the close() method. This releases the resources associated with the file and prevents potential issues with file handling.

file.close()
  • Reading from a file:

To read the entire content of a file, use the read() method.

file = open("example.txt", "r")
content = file.read()
print(content)
file.close()

To read a file line by line, you can use a for loop:

file = open("example.txt", "r")
for line in file:
    print(line.strip())
file.close()
  • Writing to a file:

To write data to a file, open it in 'w' (write) mode and use the write() method. Note that this will overwrite the file if it already exists.

file = open("output.txt", "w")
file.write("Hello, world!")
file.close()
  • Appending data to a file:

To append data to an existing file, open it in 'a' (append) mode and use the write() method.

file = open("output.txt", "a")
file.write("\nAppending this line.")
file.close()
  • Using the with statement (recommended):

To simplify file handling and ensure that the file is properly closed, you can use the with statement, which automatically closes the file after the indented block of code is executed.

with open("example.txt", "r") as file:
    content = file.read()
    print(content)

In this example, there is no need to call file.close(), as it is automatically closed by the with statement.

These are the basic operations for working with files in Python. By opening files in different modes, you can read, write, and append data as needed, while always remembering to close the file after use. The with statement is the recommended way to handle files, as it ensures proper resource management.

  1. How to open and read files in Python:

    • Description: Use the open function to open a file and the read method to read its content.
    • Code:
      file_path = "example.txt"
      
      with open(file_path, "r") as file:
          content = file.read()
          print(content)
      
  2. Writing to files in Python:

    • Description: Open a file in write mode ("w") to write content to it. Note that this truncates the file if it already exists.
    • Code:
      file_path = "example.txt"
      
      with open(file_path, "w") as file:
          file.write("Hello, World!")
      
  3. Appending data to files in Python:

    • Description: Open a file in append mode ("a") to add content to the end without truncating the existing content.
    • Code:
      file_path = "example.txt"
      
      with open(file_path, "a") as file:
          file.write("\nAppended content.")
      
  4. Closing files in Python:

    • Description: Always close files after reading or writing to release system resources.
    • Code:
      file_path = "example.txt"
      
      file = open(file_path, "r")
      content = file.read()
      file.close()
      
  5. Working with text files in Python:

    • Description: Text files contain human-readable text. Open and manipulate them using string operations.
    • Code:
      file_path = "text_file.txt"
      
      with open(file_path, "r") as file:
          content = file.read()
          print(content)
      
  6. Binary file operations in Python:

    • Description: Binary files store data in binary format. Open them in binary mode ("rb" or "wb") to work with non-text files.
    • Code:
      image_path = "image.png"
      
      with open(image_path, "rb") as file:
          binary_data = file.read()
      
  7. Handling file exceptions in Python:

    • Description: Handle exceptions like FileNotFoundError or PermissionError when working with files.
    • Code:
      try:
          with open("nonexistent_file.txt", "r") as file:
              content = file.read()
      except FileNotFoundError:
          print("File not found.")
      
  8. File modes in Python (r, w, a, etc.):

    • Description: File modes indicate the purpose of file opening (read, write, append, binary, etc.).
    • Code:
      # Read mode
      with open("example.txt", "r") as file:
          content = file.read()
      
      # Write mode
      with open("example.txt", "w") as file:
          file.write("Hello, World!")
      
      # Append mode
      with open("example.txt", "a") as file:
          file.write("\nAppended content.")
      
  9. Using with statement for file handling in Python:

    • Description: The with statement ensures that the file is properly closed, even if an exception occurs.
    • Code:
      with open("example.txt", "r") as file:
          content = file.read()
      
  10. Seek and tell operations on files in Python:

    • Description: Use seek to move the file cursor, and tell to get the current position in the file.
    • Code:
      with open("example.txt", "r") as file:
          file.seek(5)  # Move to the 6th character
          content = file.read(10)  # Read the next 10 characters
          position = file.tell()  # Get the current position
      
  11. Copying and moving files in Python:

    • Description: Use the shutil module for file operations like copying (shutil.copy) and moving (shutil.move).
    • Code:
      import shutil
      
      source_file = "example.txt"
      destination_path = "backup/example.txt"
      
      shutil.copy(source_file, destination_path)
      
  12. File compression and decompression in Python:

    • Description: Use modules like gzip or zipfile to compress and decompress files.
    • Code:
      import gzip
      
      with open("example.txt", "rb") as file:
          with gzip.open("example.txt.gz", "wb") as compressed_file:
              compressed_file.write(file.read())
      
  13. Working with CSV and JSON files in Python:

    • Description: Use the csv module for CSV files and the json module for JSON files.
    • Code:
      import csv
      import json
      
      # Reading CSV
      with open("data.csv", "r") as csv_file:
          csv_reader = csv.reader(csv_file)
          for row in csv_reader:
              print(row)
      
      # Writing JSON
      data = {"name": "John", "age": 30, "city": "New York"}
      with open("data.json", "w") as json_file:
          json.dump(data, json_file)