Study Guides (380,000)
CA (150,000)
UTSC (10,000)
Final

CSCA20H3 Study Guide - Final Guide: Backslash


Department
Computer Science
Course Code
CSCA20H3
Professor
Anna Bretscher
Study Guide
Final

This preview shows half of the first page. to view the full 2 pages of the document.
CSCA20 General Programming
1. Files
a. Open a file:
To read
open_file = open(‘filename.txt’, ‘r’)
To write – replaces file filename
open_file = open(‘filename.txt’, ‘w’)
To append
open_file = open(‘filename.txt’, ‘a’)
b. Close file after finishing:
my_file.close()
c. Reading Files:
my_file = open(‘filename’, ‘r’)
# Retrieving individual data
for line in my_file:
# split each word/data at whitespace
each_line = line.split()
# indexed line refers to all data in column ‘i’
specific_data = each_line[i]
# Read whole file at once as list of strings
list_of_lines = my_file.readlines()
# Read file one line at a time
line = my_file.readline()
# Read entire file as a string
s = my_file.read()
# Read specific number of characters
s = my_file.read(10) reads 10 characters
s = my_file.read(10) reads next 10 characters
2. Reading from a CSV(comma-separated values) file
import io
import csv
csv_file = open(‘csv_filename.csv’, ‘r’)
reader = csv.reader(csv_file)
for line in reader:
# read like an ordinary file
# but each line is a list
You're Reading a Preview

Unlock to view full version