Class XII Computer Science: File Handling Notes
Chapter 1: Python Text Files
Detailed Summary
Text files in Python are files that contain human-readable characters. Python provides a straightforward way
of interacting with these files through built-in functions. The core idea is to store data permanently on backing
storage (like HDD, SSD, USB drives) because main memory (RAM) is volatile and limited.
A text file stores data in plain text format, which can be opened using any text editor. Python provides the
`open()` function to handle text files. Files can be opened in:
- Read mode (`'r'`): Default mode, used to read content from an existing file.
- Write mode (`'w'`): Used to write new content. If the file exists, it overwrites it.
- Append mode (`'a'`): Adds new content at the end of an existing file.
Opening a file:
```python
f = open('[Link]', 'r')
```
Or, with context manager:
```python
with open('[Link]', 'r') as f:
```
Using `with` ensures that the file is automatically closed after operations.
Writing to files:
- `write()`: Writes a single string.
- `writelines()`: Writes a list of strings.
Reading from files:
- `read()`: Reads entire content.
- `read(n)`: Reads `n` characters.
Class XII Computer Science: File Handling Notes
- `readline()`: Reads one line at a time.
- `readlines()`: Reads all lines into a list.
- Using a for-loop on the file object also reads line by line.
Closing the file is crucial after writing, as buffer content must be flushed to the disk.
Example:
```python
with open('[Link]', 'w') as f:
[Link]('Hello
World
')
```
Reading example:
```python
with open('[Link]', 'r') as f:
for line in f:
print([Link]())
```
`.strip()` is used to remove leading/trailing whitespace including `
`.
Key points:
- Always close the file after operations or use `with`.
- Writing in `'w'` mode overwrites file; `'a'` mode appends.
- `print([Link]())` removes the extra blank lines in output.
Flashcards
Q: What are the two ways to open a file in Python?
Class XII Computer Science: File Handling Notes
A: Using `open()` or `with open()`.
Q: What happens if a file is opened in `'w'` mode and already exists?
A: The existing data is overwritten.
Q: How do you write a list of strings to a file?
A: Using `writelines()` method.
Q: Which method reads the whole file as a single string?
A: `read()`
Q: What's the difference between `print(data)` and `print([Link]())`?
A: `strip()` removes extra newlines/spaces.
Q: What is the benefit of using `with open()`?
A: It automatically closes the file after the block.