Interactive File Handling Python vs CPP
Interactive File Handling Python vs CPP
• Read line-by-line:
• with open("file.txt") as file:
• for line in file:
• print(line.strip())
Python File Modes
• 'r' - Read
• 'w' - Write (overwrites)
• 'a' - Append
• 'r+' - Read/Write
• Example:
• ofstream file("data.txt", ios::app);
Python vs C++
• Python:
• - Easy and short code
• - Automatic file closing
• - Ideal for scripts
• C++:
• - Manual control
• - Faster for large programs
• - Used in system software
When to Use Each?
• Use Python for:
• - Simple tasks
• - Automation, logs
• A) 'r' mode
B) 'w' mode
C) 'a' mode
D) 'r+' mode
Line-by-Line File Reading: Python vs C++
• C++: • ✔ Python is more
• while(getline(file, line)) { concise
• cout << line << endl; • ✔ 'with' auto-
• } closes the file
• ✔ 'strip()'
• Python:
removes newline
• with open("myfile.txt", "r") as characters
file:
• for line in file:
• print(line.strip())
Writing to Text Files: Python vs C++
• Python:
• with open("file.txt", "w") as f:
• f.write("Hello, World!\n")
• C++:
• #include <fstream>
• ofstream file("file.txt");
• file << "Hello, World!" << endl;
• file.close();
Appending to Text Files: Python vs C++
• Python:
• with open("file.txt", "a") as f:
• f.write("Appended Line\n")
• C++:
• ofstream file("file.txt", ios::app);
• file << "Appended Line" << endl;
• file.close();
Writing to Binary Files: Python vs C++
• Python:
• with open("file.bin", "wb") as f:
• f.write(b"\x48\x65\x6C\x6C\x6F") # 'Hello'
• C++:
• #include <fstream>
• ofstream file("file.bin", ios::binary);
• char data[] = "Hello";
• file.write(data, sizeof(data));
• file.close();
Reading Binary Files: Python vs C++
• Python:
• with open("file.bin", "rb") as f:
• data = f.read()
• print(data)
• C++:
• ifstream file("file.bin", ios::binary);
• char data[6];
• file.read(data, sizeof(data));
• cout.write(data, sizeof(data));
• file.close();
Binary File Handling (Python)
• 🔡 Characters: • 🔢 Numbers ↔ Bytes:
• - Get ASCII value of char: • - int → bytes: struct.pack('i',
ord('A') → 65 123)
• - Get char from ASCII: chr(65) • - bytes → int: struct.unpack('i',
→ 'A' data)[0]
• - Hex of char: hex(ord('H')) →
'0x48' • 📎 Notes:
• - Always open binary files with
• 📝 Strings ↔ Bytes: 'rb' or 'wb'
• - Text to bytes: • - Use 'with open(...)' for safe
"Hello".encode() → b'Hello' file handling
• - Bytes to text:
b'Hello'.decode() → 'Hello'