Professional Documents
Culture Documents
Anshu.30.da Lab Exp 3
Anshu.30.da Lab Exp 3
To perform data import and export operations in Python for CSV, Excel (XLS),
and text (TXT) files.
Code:
import csv
with open('data.csv', 'r') as file:
reader = csv.reader(file)
for row in reader:
print(row)
data = [
['Name', 'Age', 'City'],
['Alice', 30, 'New York'],
['Bob', 25, 'Los Angeles'],
['Charlie', 35, 'Chicago']
]
with open('output.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerows(data)
Code:
from openpyxl import Workbook, load_workbook
wb = load_workbook('data.xlsx')
sheet = wb.active
for row in sheet.iter_rows(values_only=True):
print(row)
wb = Workbook()
sheet = wb.active
data = [
['Name', 'Age', 'City'],
['Alice', 30, 'New York'],
['Bob', 25, 'Los Angeles'],
['Charlie', 35, 'Chicago']
]
for row in data:
sheet.append(row)
wb.save('output.xlsx')
Text (TXT):
This code uses Python's csv module for CSV file handling.
For importing data:
It reads data from 'data.csv' and prints each row.
For exporting data:
It prepares tabular data as a list of lists.
Writes this data to a new CSV file named 'output.csv'.
Overall, it showcases reading from and writing to CSV files in Python using the csv module.
Code:
with open('data.txt', 'r') as file:
for line in file:
print(line.strip())