4. Explain the concept of file handling. Also explain reading and writing access with suitable example.
Answer:
File Handling in Python
File handling lets you read from and write to files on your computer.
Modes:
'r'→ Read Mode (opens the file for reading)'w'→ Write Mode (opens the file for writing — overwrites existing content)
Example:
Writing to a File
with open('sample.txt', 'w') as f:
f.write('Hello, world!')
This creates a file named
sample.txt(or overwrites if it exists) and writes the text"Hello, world!"into it.
Reading from a File
with open('sample.txt', 'r') as f:
content = f.read()
print(content)
This reads the content of
sample.txtand prints:Hello, world!
