ICT582 Topic 07
ICT582 Topic 07
§ Collections
§ Sets
§ Dictionaries
§ Use of sets and dictionaries to solve problems
§ Sequences
§ Common characteristics of sequences
www.codemasterinstitute.com
2
This Topic
www.codemasterinstitute.com
3
Files and Directories
www.codemasterinstitute.com
5
Absolute Path
www.codemasterinstitute.com
6
Absolute Path
www.codemasterinstitute.com
11
Opening a File
www.codemasterinstitute.com
12
Opening a File
file = open("foo.txt")
filecontent = file.read()
print(filecontent)
§ The function open opens a text file foo.txt
using its relative path.
§ It returns a file object (in variable file), which
has many properties and methods for various
file operations.
§ The method read reads a number of bytes from
the file. The above statement reads the entire
content of the text file foo.txt and returns it as
a string.
www.codemasterinstitute.com
13
Function open
mode
r Open for reading (default)
r+ Like r, but also allow writing to the file
w Open for writing, truncate the file first. Create a new file if the file
doesn’t exist
w+ Like w, but also allow reading from the file
a Open for appending at the end of the file without truncating it.
Create a new file if the file doesn’t exist
a+ Like a, but also allow reading from the file
x Create a new file for writing, failing if the file already exists
www.codemasterinstitute.com
14
Text File or Binary File
www.codemasterinstitute.com
15
Text File or Binary File
www.codemasterinstitute.com
16
Text File or Binary File
§ Examples
# mode = "rt", default
file = open("foo") # mode = "rt", default
# write to the end of text file, and read from the file
file = open("foo", "a+t")
www.codemasterinstitute.com
19
Read and Write Position
www.codemasterinstitute.com
20
Read and Write Position
www.codemasterinstitute.com
21
Buffered Input/Output
www.codemasterinstitute.com
24
Close File
import csv
filepath = "staff.csv"
csvfile = open(filepath, newline='', encoding='utf-8-sig')
# create a reader object for reading lines from the csv file
# reader is an iterable object
reader = csv.reader(csvfile)
www.codemasterinstitute.com
31
Write a CSV File: writer object
www.codemasterinstitute.com
33
Getting Information about
the Operating System
import platform
print(platform.system()) # os name
print(platform.release()) # os version
print(platform.machine()) # machine type
print(platform.node()) # machine's network name
print(platform.python_version()) # Python version
import os
print(os.getcwd())
# /Users/hong/t07
os.chdir("ex1")
print(os.getcwd())
# /Users/hong/t07/ex1
os.chdir("../ex2")
print(os.getcwd())
# /Users/hong/t07/ex2
os.chdir("/Users/hong/Desktop")
print(os.getcwd())
# /Users/hong/Desktop
www.codemasterinstitute.com
35
Make and Remove Directory
import os
www.codemasterinstitute.com
36
Remove and Rename File
import os
www.codemasterinstitute.com
37
List Directory Entries
import os
www.codemasterinstitute.com
38
Summary