📄 Python File Handling – Day 17 Practice Summary
Introduction to File Handling
- File handling is used to store data for future use.
- Two main types of files:
1. Text files
2. Binary files
Opening and Closing Files
- Files are opened using `open(filename, mode)` and closed using `close()`.
Example:
```python
f = open("file.txt", "r")
f.close()
```
File Access Modes
1. `r` - Read-only (error if file doesn't exist)
2. `w` - Write-only (overwrites existing file or creates a new one)
3. `a` - Append mode (adds data at the end of file)
4. `r+` - Read and write (starts from beginning, overwrites)
5. `w+` - Write and read (overwrites existing data)
6. `a+` - Append and read (pointer at end, doesn't overwrite)
File Operations – Examples
```python
f = open('abc.txt', 'w')
f.write("I am very confident person")
f.close()
f = open('abc.txt', 'r')
data = f.read()
print(data)
f.close()
f = open('abc.txt', 'a')
f.write("And I am Strong...\n")
f.close()
f1 = open('xyz.txt', 'w')
print(f1.name, f1.mode, f1.readable(), f1.writable(), f1.closed)
f1.close()
```
File Creation and Check using `os`
```python
import os
file = "file_A.txt"
f = open('path_to_file/file_A.txt', 'w')
if os.path.isfile(file):
print("File is created")
f.write("Lines written...")
f.close()
```
Reading File Content
- `read()` – Reads entire content
- `read(n)` – Reads n characters
- `readline()` – Reads one line
- `readlines()` – Reads all lines
Example:
```python
f = open("file_A.txt", "r")
data = f.readline()
for char in data:
print(char)
f.close()
```
File Pointer Operations
- `tell()` – Returns current position of pointer
- `seek(pos)` – Moves pointer to specified position
Example:
```python
f = open("file_A.txt", "r")
print(f.tell()) # prints 0
f.seek(16)
print(f.tell()) # prints 16
f.close()
```
Using `with` Statement
- Ensures file is automatically closed after usage.
```python
with open("bbbb.txt", "w") as f:
f.write("This is cloud session")
```
Line, Word, and Character Count Program
```python
import os
filename = "file_A.txt"
if os.path.isfile(filename):
with open(filename, "r") as f:
linecnt = wordcnt = charcnt = 0
for line in f:
linecnt += 1
words = line.split()
wordcnt += len(words)
charcnt += sum(len(word) for word in words)
print("Lines:", linecnt)
print("Words:", wordcnt)
print("Characters:", charcnt)
else:
print("File not found")
```