Wednesday, September 4, 2024

PYTHON- Reading and Writing with with Statement- JSON - BINARY

 Reading and Writing with with Statement:

You can use the with statement to automatically close the file when you're done with it. It's a recommended approach as it ensures that the file is properly closed even if an exception occurs.

Sample program using the with statement:

# Writing to a file using the with statement
with open("sample.txt", "w") as file:
    file.write("Hello, World!")

# Reading from a file using the with statement
with open("sample.txt", "r") as file:
    content = file.read()
    print(content)


Handling Binary Files:

You can open files in binary mode by specifying "b" in the mode string ("rb" for reading binary, "wb" for writing binary, etc.). This is useful for working with non-text files like images or executables.

Sample program for binary file handling:

# Reading a binary file
with open("image.jpg", "rb") as file:
    binary_data = file.read()

# Writing binary data to a file
with open("copy_image.jpg", "wb") as file:
    file.write(binary_data)

These are the fundamental operations for file handling in Python. Remember to handle exceptions, check if files exist before working with them, and close files properly to avoid data corruption and resource leaks.


Advanced File Handling Functions:
In addition to the basic file handling operations mentioned earlier, Python provides more advanced file handling functions and techniques that can help you work with files more efficiently and handle various scenarios. Here are some advanced file handling functions.

Reading and Writing CSV Files:


You can use the csv module to easily read and write CSV (Comma-Separated Values) files.

Sample program to read and write CSV files:

import csv
# Writing data to a CSV file
with open("Sample_csv.csv", "w", newline="") as csvfile:
    csv_writer = csv.writer(csvfile)
    csv_writer.writerow(["Name", "Age"])
    csv_writer.writerow(["Bhaskar", 34])
    csv_writer.writerow(["Vinoth", 34])
    csv_writer.writerow(["Senthil", 37])
    csv_writer.writerow(["Venkatesh", 34])

# Reading data from a CSV file
with open("data.csv", "r") as csvfile:
    csv_reader = csv.reader(csvfile)
    for row in csv_reader:
        print(row)


Working with JSON Files:

The json module allows you to work with JSON (JavaScript Object Notation) files.

Sample program to read and write JSON files:

import json

# Writing data to a JSON file
data = {"name": "Alice", "age": 30}
with open("data.json", "w") as jsonfile:
    json.dump(data, jsonfile)

# Reading data from a JSON file
with open("data.json", "r") as jsonfile:
    loaded_data = json.load(jsonfile)
    print(loaded_data)

No comments:

Post a Comment