CSV (,)
-
(docs)[https://docs.python.org/3.12/library/csv.html#module-csv]
- stands for Comma Seperated Values
- structured data format soted as a plain text file
- commonly used to exchange speadsheets and database files
’'’csv model, releasedate,memory, CPU PC, 08-1981, 8080 (…/) ‘’’
CSV Structure
- Header (first line in a CSV file, metadata)
- Rows (data itself, each row represents a record, devided by delimiter)
- columns (each column repesents a field, devided by delimiter)
- Delimiters (can be any character)
Reading CSV files
- import csv module
- open a file object for reading
- open CSV reader object (accepts a file object as an argument)
- iterate CSV reader object (a row at a time)
- close the file object (not needed when using context manager)
import csv
csv.reader(csvfile)
- return a CSV reader object from the file object csvfile
- CSV reader object is also an iterator (put it in a for loop or convert it to a list) => file object is an iterator as well
- at each iteration it returns a row
- each row is a list of strings
- each string corresponds to a CSV column
import csv
with open ('ibmpcs.csv') as f:
# if the mode is not specified, default is read
rows = list(csv.reader(f))
# creating a reader object by passing it the file object f
# convert the iterator to list
# set the variable rows to it
header = rows[0]
# first item in rows is the header
print(f'{header[1]}\t{header[0]}')
for row in rows[1:]:
print(f'{row[1]}\t\t{row[0]}')
# iteratign through the remaining rows
# we will set the variable row to each row from the file
# we skip the first row sinc ethat is our header: using a slice starting at index 1till the end of the list
- index 1 is release date field, index zero is the model field
Writing to CSV files
- import csv module
- open file object for writing
- open a CSV writer object
- Pass the file object to it
- Call write methods in the CSV writer object (this will write our data to the file)
- Close file object (skip that when using the context manager)
import csv
csv.writer(csvfile)
- return a CSV writer object from
import csv
csvwriter.writerow(row)
- write row to the writer’s file object
- row is a container, a list of items, converted to string before written
- all items in row converted to strings before writing
- write all items in a rows to the writer’s file object
- rows is a container of containers
import csv
header = ['ID', 'Name', 'Rank']
# setting up the header
data = [
[1, 'Picard', 'Captain'],
[2, 'Crisher', 'Commander'],
[3, 'La Forge', 'Lt. Cmdr.'],
]
# a list of lists
with open ('starfleet.csv', 'w') as f:
cw = csv.writer(f)
# create a CSV file writer object
# we pass it the file object f
cw.writerow(header)
# writes one row, the header, to the CSV file
cw.writerows(data)
# we don't need to convert the ID integer
Strings | Variables | Lists | Tuples | Dictionary | ||||||
Control | Function | Files | Exceptions | |||||||
OOP | Algorithm | Data Structure | back |