Download as pdf or txt
Download as pdf or txt
You are on page 1of 4

Name : Anshu Kumar Kushwaha

Roll No. 2100290110030


Data – Analytics Lab
Exp. – 3

To perform data import and export operations in Python for CSV, Excel (XLS),
and text (TXT) files.

CSV (Comma Separated Values):


The csv module in Python provides functions to read from and write to CSV files.
Importing data from a CSV file:
We open the CSV file using open() with read mode ('r').
We create a CSV reader object using csv.reader().
Then, we iterate over each row in the CSV file using a for loop, printing each row.
Exporting data to a CSV file:
We define our data as a list of lists, where each inner list represents a row in the CSV file.
We open a new CSV file using open() with write mode ('w').
We create a CSV writer object using csv.writer().
Finally, we write all rows of data to the CSV file using writer.writerows().
In essence, csv.reader() reads CSV data from a file, and csv.writer() writes CSV data to a file,
enabling easy manipulation of tabular data in CSV format using Python.

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)

Excel (XLS or XLSX):


This code utilizes Python's csv module to handle CSV (Comma Separated Values) files.
Importing data from a CSV file:
It reads data from a CSV file named 'data.csv'.
Each row of the CSV file is printed out.
Exporting data to a CSV file:
It defines tabular data as a list of lists.
Writes this tabular data to a new CSV file named 'output.csv'.
In essence, it demonstrates how to read and write CSV files in Python using the csv module.

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())

# Exporting data to a text file


data = [
'Name: Alice, Age: 30, City: New York',
'Name: Bob, Age: 25, City: Los Angeles',
'Name: Charlie, Age: 35, City: Chicago'
]
with open('output.txt', 'w') as file:
for item in data:
file.write("%s\n" % item)

You might also like