Writing data to a file using Python

 Writing data to a file using Python

Writing data to a file in Python can be done in a variety of ways, depending on the file type and how you want to save the data. Here's a general guide to common formats.

1. Writing Text to a Plain Text File

# Writing text data

data = "This is some text data."

# Open a file in write mode ('w') and write data

with open("output.txt", "w") as file:

    file.write(data)


2. Writing Data to a CSV File

import csv

# Data to write
data = [
    ["Name", "Age", "City"],
    ["Rajesh", 25, "India"],
    ["Shaun", 30, "San Francisco"],
    ["Afzal", 35, "Chicago"]
]

# Writing to a CSV file
with open("output.csv", "w", newline="") as file:
    writer = csv.writer(file)
    writer.writerows(data)


3. Writing Data to a JSON File

import json

# Data to write
data = {
    "Name": "Alice",
    "Age": 25,
    "City": "New York"
}

# Writing to a JSON file
with open("output.json", "w") as file:
    json.dump(data, file, indent=4)


4. Writing Data to an Excel File

from openpyxl import Workbook

# Create a workbook and a sheet
wb = Workbook()
ws = wb.active
ws.title = "Sheet1"

# Writing data
data = [["Name", "Age", "City"], ["ABC", 24, "India"], ["CDE", 36, "China"]]
for row in data:
    ws.append(row)

# Save the workbook
wb.save("output.xlsx")

Comments

Popular posts from this blog

Validation Code For Phone Number Using preg_match() in Php

Update and Delete Record Using PHP and MySQL