Assignment 4 Answers
Q1:
Define the following Python file reading methods with syntax: read(), readline(), and readlines().
- read(): Reads the entire content of the file as a single string.
Example:
```python
with open("[Link]", "r") as file:
content = [Link]()
```
- readline(): Reads a single line from the file.
Example:
```python
with open("[Link]", "r") as file:
line = [Link]()
```
- readlines(): Reads all lines and returns a list.
Example:
```python
with open("[Link]", "r") as file:
lines = [Link]()
```
Q2:
What is the purpose of the write() and writelines() methods in Python?
- write(): Writes a single string to a file.
Example:
```python
with open("[Link]", "w") as file:
[Link]("Hello World")
```
- writelines(): Writes a list of strings to a file.
Example:
```python
with open("[Link]", "w") as file:
[Link](["Line 1\n", "Line 2\n", "Line 3\n"])
```
Q3:
Write a Python program to create a new file called [Link], write three lines of student data into
it, and then read the content back using read().
```python
# Writing to file
with open("[Link]", "w") as file:
[Link]("John, 85\n")
[Link]("Alice, 90\n")
[Link]("Bob, 78\n")
# Reading from file
with open("[Link]", "r") as file:
content = [Link]()
print(content)
```
Q4:
Write a program that reads a file line by line using readline() and prints only the lines that contain
more than 10 characters.
```python
with open("[Link]", "r") as file:
for line in file:
if len([Link]()) > 10:
print([Link]())
```
Q5:
Explain the difference between text mode and binary mode in file operations. Write one example for
each.
- Text Mode ('t'): Default mode; handles files as text.
Example:
```python
with open("[Link]", "r") as file:
content = [Link]()
```
- Binary Mode ('b'): Used for binary files like images or executables.
Example:
```python
with open("[Link]", "rb") as file:
data = [Link]()
```