Experiment – 1
def write_to_file(filename):
with open(filename, "w") as file:
num_students = int(input("Enter the number of students: "))
for _ in range(num_students):
name = input("Enter student name: ")
roll_no = input("Enter roll no: ")
marks = float(input("Enter marks: "))
[Link](f"{name},{roll_no},{marks}\n")
print(f"\nData saved successfully to {filename}.\n")
def read_from_file(filename):
print("\nStudent Details:")
with open(filename, "r") as file:
for line in file:
name, roll_no, marks = [Link]().split(",")
print(f"Name: {name}, Roll number: {roll_no}, Marks: {marks}")
def main():
filename = "[Link]"
while True:
print("\n--- Student Marks Management ---")
print("1. Write student details")
print("2. Read student details")
print("3. Exit")
choice = input("Enter your choice: ")
if choice == "1":
write_to_file(filename)
elif choice == "2":
read_from_file(filename)
elif choice == "3": else:
print("Exiting program") print("Invalid choice! Please try again.")
break main()
Experiment – 2
import csv
def read_csv_as_dict(filename):
try:
with open(filename, mode='r') as file:
csv_reader = [Link](file)
print("\nCSV File Contents:")
for row in csv_reader:
print(dict(row))
except FileNotFoundError:
print(f"Error: The file '{filename}' was not found.")
except Exception as e:
print(f"An error occurred: {e}")
def main():
filename = input("Enter the CSV file name (with .csv extension): ")
read_csv_as_dict(filename)
main()
Experiment – 3
import json
# Data to write
data = {
"name": "Alice",
"age": 30,
"city": "New York"
}
# Writing to a JSON file
with open('[Link]', mode='w') as file:
[Link](data, file, indent=4) # 'indent=4' makes the file readable
Experiment – 4
import [Link] as ET
# Parse the XML file
tree = [Link]("[Link]")
root = [Link]()
# Extract and print employee details
for employee in [Link]('employee'):
name = [Link]('name').text
age = [Link]('age').text
print(f"Name: {name}, Age: {age}")
Experiment – 5
import pandas as pd
import numpy as np
# Import the Excel file into a Pandas DataFrame
file_path = '[Link]' # Replace with your file path
df = pd.read_excel(file_path)
# a. Get the data types of the given Excel data
print("Data Types of Each Column:")
print([Link])
# b. Display the last five rows
print("\nLast 5 Rows of the DataFrame:")
print([Link](5))
# c. Insert a column in the sixth position and fill it with NaN values
#[Link](5, 'New_Column', [Link]) # Index 5 corresponds to the 6th column
print("\nDataFrame After Adding New Column:")
print([Link]()) # Display the first few rows to confirm the new column
# Optional: Save the modified DataFrame to a new Excel file
output_file_path = '[Link]'
df.to_excel(output_file_path, index=False)
print(f"\nModified DataFrame saved to {output_file_path}")
Experiment – 6
from pdfminer.high_level import extract_text
# Extract text from a PDF file
text = extract_text("[Link]")
# Print the extracted text
print(text)
Program 7
import pandas as pd
file_path = "[Link]"
xls = [Link](file_path)
print("Available Sheets:", xls.sheet_names)
for sheet in xls.sheet_names:
df = pd.read_excel(xls, sheet_name=sheet)
print(f"\nData from Sheet: {sheet}")
print([Link]()) # Show first 5 rows
output_csv = f"{sheet}.csv"
df.to_csv(output_csv, index=False)
print(f"Saved {sheet} data as {output_csv}")
Program 8
import sqlite3
conn = [Link]('[Link]')
cursor = [Link]()
[Link]("""
CREATE TABLE IF NOT EXISTS salesman (
salesman_id INTEGER,
name TEXT,
city TEXT,
commission REAL
);
""")
s_id = input('Salesman ID: ')
s_name = input('Name: ')
s_city = input('City: ')
s_commission = float(input('Commission: ')) # Convert commission to float
try:
[Link]("""
INSERT INTO salesman (salesman_id, name, city, commission)
VALUES (?, ?, ?, ?)
""", (s_id, s_name, s_city, s_commission))
[Link]() # Commit the transaction
print('Data entered successfully.')
except [Link] as e:
print(f'An error occurred: {e}')
finally:
[Link]() # Close the connection
print("\nThe SQLite connection is closed.")
Program 10
import agate
table = [Link].from_csv('[Link]')
print("Table Columns:")
print([[Link] for column in [Link]])
print("\nFirst 5 Rows of the Table:")
table.print_table(max_rows=5)
print("\nSummary Statistics:")
for column in [Link]:
if isinstance(column.data_type, [Link]):
print(f"{[Link]}:")
print(f" Mean: {[Link]([Link]([Link]))}")
print(f" Median: {[Link]([Link]([Link]))}")
print(f" Max: {[Link]([Link]([Link]))}")
print(f" Min: {[Link]([Link]([Link]))}")
col1 = 'CPI 2013 Score'
col2 = 'Total (%)'
from [Link] import pearsonr
col1 = [float(value) for value in [Link]['CPI 2013 Score'] if isinstance(value, (int, float))]
col2 = [float(value) for value in [Link]['Total (%)'] if isinstance(value, (int, float))]
print([Link]['CPI 2013 Score'])
print([Link]['Total (%)'])
Program 11
import [Link] as plt
# pip install matplotlib
# Sample dataset: CPI 2013 Scores vs Child Labor Percentages
data = [
{'Country': 'Country A', 'CPI 2013 Score': 90, 'Total (%)': 5},
{'Country': 'Country B', 'CPI 2013 Score': 80, 'Total (%)': 15},
{'Country': 'Country C', 'CPI 2013 Score': 70, 'Total (%)': 25},
# Extracting data for plotting
cpi_scores = [item['CPI 2013 Score'] for item in data]
child_labour_percentages = [item['Total (%)'] for item in data]
countries = [item['Country'] for item in data]
# Creating the scatter plot
[Link](figsize=(10, 6))
[Link](cpi_scores, child_labour_percentages, color='blue')
# Annotate points with country names
for i, country in enumerate(countries):
[Link](country, (cpi_scores[i], child_labour_percentages[i]))
# Adding titles and labels
[Link]('CPI Score - 2013')
[Link]('Child Labour Percentage (%)')
[Link]('CPI & Child Labor Correlation')
[Link](True)
[Link]()
Program 12
import pygal
from [Link] import Style
custom_style = Style(
background='white',
plot_background='white',
foreground='black',
foreground_strong='black',
foreground_subtle='gray',
colors=('#E88080', '#404040', '#9BCB50')
child_labour_data = {
'in': 10, # India
'pk': 12, # Pakistan
'bd': 15, # Bangladesh
'ng': 25, # Nigeria
'cn': 5, # China
'us': 1, # United States
'br': 7, # Brazil
'za': 8, # South Africa
'et': 30, # Ethiopia
'eg': 15 # Egypt
worldmap = [Link](style=custom_style)
[Link] = 'Child Labour Worldwide (%)'
[Link]('Child Labour (%)', child_labour_data)
worldmap.render_to_file('[Link]')
print("World map has been saved as '[Link]'.")
Program 13
import requests
# Fetch the [Link] file from Wikipedia
response = [Link]("[Link]
test = [Link]
# Display the content
print("[Link] for [Link]
print("=" * 60)
print(test)