1
1
Aaron Stevens
6 February 2009
CS108 Lecture 09: Computing with Text
Reading and writing files
2
Overview/Questions
– Review: string operators and operations
- Additional examples, if needed
Overview/Questions Review: string operators and operations - - PDF document
CS108 Lecture 09: Computing with Text Reading and writing files Aaron Stevens 6 February 2009 1 Overview/Questions Review: string operators and operations Additional examples, if needed How else can we manipulate text? How
1
Reading and writing files
2
3
– Storage of data when computer is off – Batch input: processing large amounts of data without typing input at the keyboard – Batch output: processing large amounts of data without needing to read it all from the screen
4
Pictured: Windows Explorer (left) and Finder (right), showing directories and files stored on my computer.
5
6
text alcohol.txt jane.txt
/ Directory Files Directory
7
Directory tree A logical view of the nested directory organization of a file system. Each directory is a branch, and each file is a leaf. Root directory The directory at the highest level. Every directory descends from the root. Parent directory Every directory has a parent, up to the root. Subdirectory A directory contained within another directory.
8
An Example of the Windows directory tree.
9
An Example of a UNIX directory tree; Mac OS is based on BSD UNIX.
10
11
If present working directory is
/home/fac3/azs
Then the relative path alcohol.txt is sufficient.
12
13
Some common file types and their extensions. Microsoft pioneered the 8.3 filename standard.
For more info, see http://filext.com/faq/file_extension_information.php
14
15
16
17
18
19
<filevar> = open(<filename>,<mode>)
>>> f = open("c:/text/alcohol.txt") >>> for line in f: ... print line >>> f.close()
20
>>> f = open("c:/text/output.txt", "w") >>> f.write("Some text to the file\n") >>> f.write("Some more text to the file\n") >>> f.write("Enough already!\n") >>> f.close()
21
22
http://mcsp.wartburg.edu/zelle/python/graphics.py, and save it in your code folder (with your examples).