-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path29_FileHandling.py
More file actions
38 lines (31 loc) · 898 Bytes
/
29_FileHandling.py
File metadata and controls
38 lines (31 loc) · 898 Bytes
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
# Opening a File in Python
# file = open('filename.txt', 'mode')
# Basic Example: Opening a File
# with open("C:/Users/akhil/OneDrive/Desktop/Numpy/codeharry_numpy.py", "r") as f:
# print(f.read())
# Checking File Properties
f = open("01_Basics.py", "r")
print("Filename:", f.name)
print("Mode:", f.mode)
print("Is Closed:", f.closed)
# Closing a File
f.close()
print("Is Closed after closing:", f.closed)
# Reading from a File
file = open("01_Basics.py", "r")
content = file.read()
print(content)
file.close()
# Writing to a File
with open("sample.txt", "w") as file:
file.write("Hello, World!\n")
file.write("This is a sample file.\n")
file.write("Writing to files in Python is easy!")
print("Data written to sample.txt")
# Handling Exceptions when closing a File
try:
f = open("02_Datatypes.py", "r")
content = f.read()
print(content)
finally:
file.close()