-
Notifications
You must be signed in to change notification settings - Fork 0
/
lesson14.py
64 lines (55 loc) · 1.43 KB
/
lesson14.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# Lesson 14 Files
print('1') # notice the extra new lines
fhand = open('testing.txt')
for line in fhand :
print(line)
print('2') # newline erased by rstrip()
fhand = open('testing.txt')
for line in fhand :
line = line.rstrip()
print(line)
print('3') # the whole text is passed to a variable (not recommended for huge files)
fhand = open('testing.txt')
txt = fhand.read()
print(txt)
print('length', len(txt))
print('starts with: ', txt[:20])
print('4') # a counter of lines
fhand = open('testing.txt')
counter = 0
for line in fhand :
counter = counter + 1
print('num of lines:', counter)
print('5') # using if
fhand = open('testing.txt')
for line in fhand :
line = line.rstrip()
if line.startswith('good') :
print('selected line: ', line)
print('6') # using if not & continue
fhand = open('testing.txt')
for line in fhand :
line = line.rstrip()
if not line.startswith('good') :
continue
print('selected line: ', line)
print('7') # using in
fhand = open('testing.txt')
for line in fhand :
line = line.rstrip()
if 'good' in line :
print('selected line: ', line)
print('8') # using input
while True :
fname = input('Please write the file name to read or "quit" to exit >>>')
if fname == 'quit' :
break
try :
fhand = open(fname)
except :
print('error. name invalid.')
continue
break
for line in fhand :
line = line.rstrip()
print(line)