-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwk 5
41 lines (37 loc) · 1.17 KB
/
wk 5
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
# File Creation
def create_file():
try:
with open("my_file.txt", "w") as file:
file.write("This is line 1\n")
file.write("12345\n")
file.write("Another line here\n")
print("File 'my_file.txt' created successfully.")
except Exception as e:
print(f"Error creating file: {e}")
# File Reading and Display
def read_file():
try:
with open("my_file.txt", "r") as file:
content = file.read()
print("Contents of 'my_file.txt':")
print(content)
except FileNotFoundError:
print("File 'my_file.txt' not found.")
except PermissionError:
print("Permission denied to access 'my_file.txt'.")
except Exception as e:
print(f"Error reading file: {e}")
# File Appending
def append_to_file():
try:
with open("my_file.txt", "a") as file:
file.write("Appending line 1\n")
file.write("67890\n")
file.write("Yet another line\n")
print("Content appended to 'my_file.txt' successfully.")
except Exception as e:
print(f"Error appending to file: {e}")
create_file()
read_file()
append_to_file()
read_file()