Program 01
Import & export files
Import and export datasets in CSV, Excel and JSON using Pandas.
Algorithm
1. Start 2. Build a small DataFrame from a dict 3. Write it with to_csv / to_json / to_excel (index=False) 4. Read each file back with read_csv / read_json / read_excel and print 5. Stop
Program
import pandas as pd
df = pd.DataFrame({'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 30, 35]})
df.to_csv('01.csv', index=False)
df.to_json('01.json', orient='records')
df.to_excel('01.xlsx', index=False)
print("CSV Data:\n", pd.read_csv('01.csv'))
print("\nJSON Data:\n", pd.read_json('01.json'))
print("\nExcel Data:\n", pd.read_excel('01.xlsx'))Output
CSV Data:
Name Age
0 Alice 25
1 Bob 30
2 Charlie 35
JSON Data:
Name Age
0 Alice 25
1 Bob 30
2 Charlie 35
Excel Data:
Name Age
0 Alice 25
1 Bob 30
2 Charlie 35Viva: which module is used and why
Q. Why import pandas as pd?
A. pandas: tables (DataFrame) and file I/O. pd is just a short name so we can type pd.something.
Viva: what does each line do?
df = pd.DataFrame({'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 30, 35]})pd.DataFrame builds a table from the dict: each key becomes a column. The result is stored in df.
df.to_csv('01.csv', index=False)to_csv() writes the DataFrame to a .csv file. index=False stops pandas saving the row numbers as an extra column.
df.to_json('01.json', orient='records')to_json() writes the DataFrame to a .json file. orient='records' writes JSON as one object per row.
df.to_excel('01.xlsx', index=False)to_excel() writes the DataFrame to an .xlsx file. index=False stops pandas saving the row numbers as an extra column.
print("CSV Data:\n", pd.read_csv('01.csv'))Prints "CSV Data:" with the result. pd.read_csv() loads a .csv file into a DataFrame.
print("\nJSON Data:\n", pd.read_json('01.json'))Prints "JSON Data:" with the result. pd.read_json() loads a .json file into a DataFrame.
print("\nExcel Data:\n", pd.read_excel('01.xlsx'))Prints "Excel Data:" with the result. pd.read_excel() loads an .xlsx sheet into a DataFrame (needs openpyxl).
Viva: concepts
Q. Why pass index=False to to_csv()?
A. So the row numbers are not saved as an extra column. Without it, reading the file back gives you an extra 'Unnamed: 0' column.
Q. Which package does pandas use to write .xlsx files?
A. openpyxl. openpyxl reads and writes .xlsx. xlrd only reads the old .xls format.
Q. to_json(orient='records') writes…
A. A list of row objects: [{...}, {...}]. 'records' gives one JSON object per row, which is the most readable layout.
Viva: "change it to…"
→ Add a City column
df['City'] = ['Delhi', 'Pune', 'Goa']→ Show only the first 2 rows of the CSV
print(pd.read_csv('01.csv').head(2))→ Save JSON one object per column instead
df.to_json('01.json')






















