Page 1 of 1

File Operations - Text File

Posted: Tue Apr 15, 2025 9:05 am
by admin

Code: Select all

# --- File: file_operations_demo.py ---

# 1. Writing to a file (this will create the file if it doesn't exist)
with open("financial_data.txt", "w") as file:
    file.write("Year,Revenue,Expense\n")
    file.write("2022,1000000,400000\n")
    file.write("2023,1200000,500000\n")

print("File created and data written using 'w' mode.")

Code: Select all

# 2. Reading the entire file content
with open("financial_data.txt", "r") as file:
    content = file.read()
    print("\nReading the file content:\n")
    print(content)

Code: Select all

# 3. Appending new data to the file
with open("financial_data.txt", "a") as file:
    file.write("2024,1400000,600000\n")

print("\nNew data appended using 'a' mode.")

Code: Select all

# 4. Reading line by line
print("\nReading file line by line:")
with open("financial_data.txt", "r") as file:
    for line in file:
        print(line.strip())

Code: Select all

# 5. Using readlines() to read all lines into a list
print("\nUsing readlines() to store lines as a list:")
with open("financial_data.txt", "r") as file:
    lines = file.readlines()
    print(lines)

# Optional: Close is handled by 'with' block automatically, but here's manual closing:
file = open("financial_data.txt", "r")
print("\nManual close demo (not required when using 'with'):")
print(file.readline())
file.close()

Re: File Operations - CSV File

Posted: Tue Apr 15, 2025 9:05 am
by admin

Code: Select all

import csv

# Writing to a CSV file
with open("salary_data.csv", mode="w", newline="") as file:
    writer = csv.writer(file)
    writer.writerow(["Name", "Month", "Salary"])
    writer.writerow(["Anuj", "April", 50000])
    writer.writerow(["Meena", "April", 60000])
print("Initial CSV data written.")

Code: Select all

# Appending rows to the CSV file
with open("salary_data.csv", mode="a", newline="") as file:
    writer = csv.writer(file)
    writer.writerow(["Karan", "April", 55000])
    writer.writerow(["Sneha", "April", 62000])
print("New rows appended to CSV.")

Code: Select all

# Reading from the CSV file
print("\nReading data from CSV:")

with open("salary_data.csv", mode="r") as file:
    reader = csv.reader(file)
    next(reader)  # Skip header
    for row in reader:
        name, month, salary = row
        if int(salary) > 55000:
            print(f"- {name} earns more than ₹55,000")

Re: File Operations - Excel File

Posted: Tue Apr 15, 2025 9:05 am
by admin

Code: Select all

import pandas as pd

# Creating initial Excel file
data = {
    "Name": ["Anuj", "Meena"],
    "Month": ["April", "April"],
    "Salary": [50000, 60000]
}
df = pd.DataFrame(data)
df.to_excel("salary_data.xlsx", index=False, engine='openpyxl')
print("Initial Excel file created.")

# Appending data to Excel (read, append, save again)
new_data = pd.DataFrame({
    "Name": ["Karan", "Sneha"],
    "Month": ["April", "April"],
    "Salary": [55000, 62000]
})

existing_data = pd.read_excel("salary_data.xlsx", engine='openpyxl')
updated_data = pd.concat([existing_data, new_data], ignore_index=True)
updated_data.to_excel("salary_data.xlsx", index=False, engine='openpyxl')
print("New data appended to Excel.")

# Reading and filtering data
df = pd.read_excel("salary_data.xlsx", engine='openpyxl')
print("\nEmployees earning more than ₹55,000:")
print(df[df["Salary"] > 55000]["Name"].to_string(index=False))

Re: File Operations - Text File

Posted: Thu Dec 11, 2025 12:17 pm
by admin

Code: Select all

import pandas as pd

# Example dataframes
df_sales = pd.DataFrame({
    "Product": ["A", "B", "C"],
    "Qty": [10, 20, 30]
})

df_customers = pd.DataFrame({
    "Customer": ["X", "Y", "Z"],
    "City": ["Chennai", "Coimbatore", "Madurai"]
})

output_file = "multi_sheet_report.xlsx"

try:
    # engine="openpyxl" for append or existing file modifications
    with pd.ExcelWriter(output_file, engine="xlsxwriter") as writer:
        df_sales.to_excel(writer, sheet_name="Sales", index=False)
        df_customers.to_excel(writer, sheet_name="Customers", index=False)
    print("Excel saved successfully.")
except Exception as e:
    print("Error:", e)

Re: File Operations - excel file with index

Posted: Thu Dec 11, 2025 12:33 pm
by admin

Code: Select all

import pandas as pd
from openpyxl import load_workbook
from openpyxl.utils import get_column_letter
from openpyxl.styles import Font

# Sample data
df_sales = pd.DataFrame({"Product": ["A", "B"], "Qty": [10, 20]})
df_customers = pd.DataFrame({"Customer": ["X", "Y"], "City": ["Chennai", "Madurai"]})

datasets = {
    "Sales": df_sales,
    "Customers": df_customers,
}

output_file = "excel_with_index.xlsx"

# Step 1: Write all sheets
with pd.ExcelWriter(output_file, engine="openpyxl") as writer:
    for sheet, df in datasets.items():
        df.to_excel(writer, sheet_name=sheet, index=False)

# Step 2: Reopen workbook to add Index sheet with hyperlinks
wb = load_workbook(output_file)

# Create Index sheet as first sheet
index_sheet = wb.create_sheet("Index", 0)

index_sheet["A1"] = "Sheet Name"
index_sheet["B1"] = "Open Sheet"

index_sheet["A1"].font = Font(bold=True)
index_sheet["B1"].font = Font(bold=True)

row = 2

for sheet_name in datasets.keys():
    # Write sheet name
    index_sheet[f"A{row}"] = sheet_name
    
    # Create hyperlink in column B
    link_formula = f"=HYPERLINK(\"#{sheet_name}!A1\", \"Go to {sheet_name}\")"
    index_sheet[f"B{row}"] = link_formula
    index_sheet[f"B{row}"].font = Font(color="0000FF", underline="single")

    row += 1

# Optional: Auto column width
for col in range(1, 3):
    column_letter = get_column_letter(col)
    index_sheet.column_dimensions[column_letter].width = 25

wb.save(output_file)

print("Excel file created with Index sheet and hyperlinks.")