Show Menu
Cheatography

BC3407 Cheat Sheet (DRAFT) by

A cheat sheet for BC3407 Practical Assessment

This is a draft cheat sheet. It is a work in progress and is not finished yet.

Methods for dict

len(dict_name) # the no. of items in this dictionary
dict_name.clear() # empty the dictionary
dict_name.items() # pairs of key value
dict_name.keys() # all keys in the dictionary
dict_name.values() # all values in the dictionary

Text File I/O

Reading
file_pointer = open("data.txt", "r")
for each_line in file_pointer:
    
print(each_line)
file_pointer.close()
Other Reading:
with open("file.txt", "r") as file:
    
content = file.read()
    
# f.readline(): line by line as a string
    
# f.readlines(): as a single list
    
print(content)
Writing:
# f.write(s), f.writelines(lines) - list of string
file_pointer = open("line.txt", "w")
data_list = ["l1", "l2"]
for each_line in data_list:
    
print(each_line, file=file_pointer)
file_pointer.close()
Other Writing: data_list = ["l1", "l2"] with open("data.txt", "w") as file_pointer:     for each in data_list:         file_pointer.write(each)

CSV File I/O

CSV Reading
import csv
data_row = ['Data1', 'Data2', 'Data3']
with open("data.csv", "r") as file_pointer:
    
csv_pointer = csv.reader(file_pointer)
    
for each in csv_pointer:
        
print(each) #type(each) = list
CSV Writing with open("data.csv", "w") as file_pointer:     csv_pointer = csv.writer(file_pointer)     csv_pointer.writerow(data_row)

JSON File I/O

JSON dump
import json
kelvin = {}
kelvin['Name'] = 'Kelvin Lee'
kelvin['income'] = 5300
kelvin['children'] = [{'Name: 'Alice', 'age':6}]
with open("profile.json","w") as write_f:
    
json.dump(kelvin, write_f, indent=6)
JSON load
with open("profile.json","r") as read_f:
    
kelvin = json.load(read_file)
print(kelvin["Name"])
for c in kelvin['children']:
    
print(c['age'], c['Name'])

Object File (Pickling - object --> byte stream)