-
Notifications
You must be signed in to change notification settings - Fork 0
/
file_handling_assignment.py
56 lines (46 loc) · 1.58 KB
/
file_handling_assignment.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
def create_file():
try:
with open("my_file.txt", "w") as file:
file.write("Python is a versatile language.\n")
file.write("12345\n")
file.write("Another line with some numbers: 98765\n")
except PermissionError:
print("Permission denied to create the file.")
except Exception as e:
print("An error occurred:", e)
finally:
print("File creation completed.")
def read_file():
try:
# Open "my_file.txt" in read mode ('r')
with open("my_file.txt", "r") as file:
# Read and display the contents of the file
print("Contents of my_file.txt:")
print(file.read())
except FileNotFoundError:
print("File not found.")
except PermissionError:
print("Permission denied to read the file.")
except Exception as e:
print("An error occurred:", e)
def append_file():
try:
# Open "my_file.txt" in append mode ('a')
with open("my_file.txt", "a") as file:
# Append three additional lines of text to the existing content
file.write("Appending line 1.\n")
file.write("Appending line 2.\n")
file.write("Appending line 3.\n")
except PermissionError:
print("Permission denied to append to the file.")
except Exception as e:
print("An error occurred:", e)
finally:
print("File appending completed.")
# Main function to execute the tasks
def main():
create_file()
read_file()
append_file()
if __name__ == "__main__":
main()