-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtry_catch.py
More file actions
69 lines (63 loc) · 2.14 KB
/
try_catch.py
File metadata and controls
69 lines (63 loc) · 2.14 KB
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
65
66
67
68
69
x = int(input ('plesae enter a number between 1 and 5:'))
if x < 1 or x > 5:
raise ValueError('the number should be between 1 and 5')
print(f"3 / x {3 / x}")
try:
x = int(input ('plesae enter a number between 1 and 5:'))
if x < 1 or x > 5:
raise ValueError('the number should be between 1 and 5')
except (ValueError) as e:
print(f"Caught a value error: ")
else:
print(f"3 / x {3 / x}")
finally:
print('We made it!')
class FileManipulator:
def __init__(self, fileName):
self.contents = None
while self.contents == None:
try:
myfile = open(fileName, 'r') # Open a file for
self.contents = myfile.readlines() # Read in the content by line.
except (FileNotFoundError, TypeError, OSError) as e:
print(type(e), e)
fileName = input("Please enter a valid file name: ")
else:
myfile.close()
def reverse(self,fileName):
while True:
try:
myfile = open(fileName, 'w') # Open a file for writing
revContent = [x.strip()[::-1] for x in self.contents]
for i in range(len(revContent)):
if i == (len(revContent)-1):
myfile.write(revContent[i])
else:
myfile.write(revContent[i] + '\n') # write desired output to file
except (FileNotFoundError, TypeError, OSError) as e:
print(type(e),e)
fileName = input("Please enter a valid file name: ")
else:
myfile.close()
break
#bonus
def upper(self,fileName):
while True:
try:
myfile = open(fileName, 'w') # Open a file for writing
upperContent = [x.strip().upper() for x in self.contents]
for i in range(len(upperContent)):
if i == (len(upperContent)-1):
myfile.write(upperContent[i])
else:
myfile.write(upperContent[i] + '\n') # write desired output to file
except (FileNotFoundError, TypeError, OSError) as e:
print(type(e),e)
fileName = input("Please enter a valid file name: ")
else:
myfile.close()
break
f = FileManipulator("tm.txt")
print(f.contents)
f.reverse("tmp2.txt")
f.upper("tmp3.txt")