Skip to content

Commit 67d5471

Browse files
authored
Add files via upload
1 parent b389d2f commit 67d5471

File tree

8 files changed

+134208
-0
lines changed

8 files changed

+134208
-0
lines changed

Chapter 07: Files/ch07_file.py

Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
1+
# 1.file hande as a sequence
2+
handle = open('test.txt')
3+
for cheese in handle:
4+
print(cheese)
5+
# cheese means iteration variable, print out each line of file test.txt
6+
print('#####################################################')
7+
# 2.counting lines in a file
8+
handle = open('test.txt')
9+
count = 0
10+
for line in handle:
11+
count = count+1
12+
print('Line count:', count)
13+
# 2.counting lines in a file
14+
handle = open('mbox.txt')
15+
count = 0
16+
for line in handle:
17+
count = count+1
18+
print('Line count:', count)
19+
# "line" is just a random name of iteration variable!
20+
print('#####################################################')
21+
print('3.Reading the *whole* file')
22+
print('you can red the whole file (newline and all) '
23+
'into a single string')
24+
fhand = open('test.txt')
25+
ghand = open('test.txt', 'r')
26+
# you have to use string.read() to read whole thing into string,
27+
# also read newline as "\n"
28+
inp = fhand.read()
29+
print(len(inp)) # print the length of the file
30+
print(inp)
31+
print('fhand is', fhand)
32+
print('ghand is', ghand)
33+
# means 'r' in open doesn't read the file
34+
print(inp[:20]) # print out the first 20 letters
35+
# (not included the 20th character!)
36+
print('#####################################################')
37+
# 4.Search through a file
38+
print('put an "if" statement in "for" loop '
39+
'to only print out certain lines')
40+
fhand = open('mbox_short.txt')
41+
for line in fhand:
42+
if line.startswith('From: '):
43+
print(line)
44+
# already checked, all lines meet the criteria are printed out
45+
# Problem: lots of blank line between each line.
46+
# Reason: 1. each line from the file has a "newline" at the end
47+
# 2. "print" statement add "newline" to each line
48+
#Solution: strip the whitespace from
49+
# the right-hand side of the string using "rstrip()"
50+
# newline is considered as whitespace
51+
print('fixed version: strip newline:')
52+
fhand = open('mbox_short.txt')
53+
for line in fhand:
54+
if line.startswith('From: '):
55+
print(line.rstrip())
56+
# or print('fixed version: strip newline:')
57+
# fhand = open('mbox_short.txt')
58+
# for line in fhand:
59+
# line = line.rstrip() <---------------------
60+
# if line.startswith('From: '):
61+
# print(line)
62+
print('#####################################################')
63+
print('4.skipping with continue')
64+
print('we can conveniently skip a line by '
65+
'using "continue" statement')
66+
fhand = open('test.txt')
67+
for line in fhand:
68+
line = line.rstrip()
69+
if line.startswith('From: '):
70+
continue
71+
print(line)
72+
print('*******************')
73+
fhand = open('test.txt')
74+
for line in fhand:
75+
line = line.rstrip()
76+
# Skip 'uninteresting lines'
77+
if not line.startswith('From:'):
78+
continue
79+
# Process our 'interesting' line
80+
print(line)
81+
print('#####################################################')
82+
print('5. Usnig "in" to select lines')
83+
print('we can find a string in a line as our selection criteria')
84+
fhand = open('test.txt')
85+
for line in fhand:
86+
line = line.rstrip()
87+
if not '@uct.ac.za' in line:
88+
continue
89+
print(line)
90+
print('**********************')
91+
fhand = open('test.txt')
92+
for line in fhand:
93+
line = line.rstrip()
94+
if line.find('@uct.ac.za')== -1:
95+
continue
96+
print(line)
97+
print(line.find('@uct.ac.za'))
98+
#'find' statement: either returns the position of the string
99+
# or -1 if the string was not found
100+
print('#####################################################')
101+
print('6.promp with file name')
102+
fname = input('Enter the file name: ')
103+
try:
104+
fhand = open(fname)
105+
except:
106+
print('File cannot be opened:', fname)
107+
exit()
108+
subject = input('we gonna find: ')
109+
count =0
110+
for line in fhand:
111+
line = line.rstrip()
112+
if line.startswith(subject):
113+
count = count+1
114+
print('there are', count, 'subject lines in', fname )
115+
print('#####################################################')

Chapter 07: Files/ch07_hw1.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
print('Exercise 1: Write a program to read through a file and '
2+
'print the contents of the file (line by line) all in upper case.')
3+
fname = open ('mbox.txt')
4+
for line in fname:
5+
line = line.rstrip()
6+
print(line.upper())

Chapter 07: Files/ch07_hw2.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
2+
# Use the file name mbox-short.txt as the file name
3+
fname = input("Enter file name: ")
4+
fh = open(fname)
5+
sum = 0.0
6+
count = 0
7+
8+
for line in fh:
9+
line = line.rstrip()
10+
if not line.startswith("X-DSPAM-Confidence:"):
11+
continue
12+
sum = sum + float(line[20:])
13+
count = count + 1
14+
15+
print("Average spam confidence:", sum/count)

Chapter 07: Files/ch07_quiz

Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
Question 1
2+
Given the architecture and terminology we introduced in Chapter 1, where are files stored?
3+
Motherboard
4+
Central Processor
5+
Machine Language
6+
Secondary memory
7+
8+
Answer: Secondary memory
9+
10+
Question 2
11+
What is stored in a "file handle" that is returned from a successful open() call?
12+
The handle has a list of all of the files in a particular folder on the hard drive
13+
The handle is a connection to the file's data
14+
The handle contains the first 10 lines of a file
15+
All the data from the file is read into memory and stored in the handle
16+
17+
Answer: The handle is a connection to the file's data
18+
19+
Question 3
20+
What do we use the second parameter of the open() call to indicate?
21+
How large we expect the file to be
22+
The list of folders to be searched to find the file we want to open
23+
Whether we want to read data from the file or write data to the file
24+
What disk drive the file is stored on
25+
26+
Question 4
27+
What Python function would you use if you wanted to prompt the user for a file name to open?
28+
file_input()
29+
read()
30+
raw_input()
31+
cin
32+
33+
Answer: raw_input()
34+
35+
Question 5
36+
What is the purpose of the newline character in text files?
37+
It adds a new network connection to retrieve files from the network
38+
It indicates the end of one line of text and the beginning of another line of text
39+
It enables random movement throughout the file
40+
It allows us to open more than one files and read them in a synchronized manner
41+
42+
Answer: It indicates the end of one line of text and the beginning of another line of text
43+
44+
Question 6
45+
If we open a file as follows:
46+
xfile = open('mbox.txt')
47+
What statement would we use to read the file one line at a time?
48+
49+
for line in xfile:
50+
while ( getline (xfile,line) ) {
51+
READ xfile INTO LINE
52+
READ (xfile,*,END=10) line
53+
54+
Answer: for line in xfile
55+
56+
Question 7
57+
What is the purpose of the following Python code?
58+
fhand = open('mbox.txt')
59+
x = 0
60+
for line in fhand:
61+
x = x + 1
62+
print x
63+
Count the lines in the file 'mbox.txt'
64+
Reverse the order of the lines in mbox.txt
65+
Remove the leading and trailing spaces from each line in mbox.txt
66+
Convert the lines in mbox.txt to upper case
67+
68+
Answer: Count the lines in the file 'mbox.txt'
69+
70+
Question 8
71+
If you write a Python program to read a text file and you see extra blank lines in the output that are not present in the file input as shown below, what Python string function will likely solve the problem?
72+
73+
74+
75+
76+
77+
78+
79+
...
80+
find()
81+
startswith()
82+
rstrip()
83+
split()
84+
Answer: rstrip()
85+
86+
Question 9
87+
The following code sequence fails with a traceback when the user enters a file that does not exist. How would you avoid the traceback and make it so you could print out your own error message when a bad file name was entered?
88+
fname = raw_input('Enter the file name: ')
89+
fhand = open(fname)
90+
try / except
91+
signal handlers
92+
try / catch / finally
93+
on error resume next
94+
95+
Answer: try/ except
96+
97+
Question 10
98+
What does the following Python code do?
99+
fhand = open('mbox-short.txt')
100+
inp = fhand.read()
101+
Checks to see if the file exists and can be written
102+
Turns the text in the file into a graphic image like a PNG or JPG
103+
Reads the entire file into the variable inp as a string
104+
Prompts the user for a file name
105+
106+
Answer: Reads the entire file into the variable inp as a string

0 commit comments

Comments
 (0)