File Handling in Python vs C++
1. Creating Files
**Python**:
```python
file = open("example.txt", "w")
file.write("Hello from Python!\n")
file.close()
```
**C++**:
```cpp
#include <fstream>
using namespace std;
int main() {
ofstream file("example.txt");
file << "Hello from C++!\n";
file.close();
return 0;
}
```
2. Reading and Writing
**Python**:
```python
with open("data.txt", "w") as f:
f.write("Python rocks!\n")
with open("data.txt", "r") as f:
print(f.read())
```
**C++**:
File Handling in Python vs C++
```cpp
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream out("data.txt");
out << "C++ rocks!\n";
out.close();
ifstream in("data.txt");
string line;
while (getline(in, line))
cout << line << endl;
in.close();
return 0;
}
```
3. File Modes
**Python Modes:**
- 'r': Read
- 'w': Write
- 'a': Append
- 'r+': Read/Write
**C++ Modes:**
- ios::in: Read
- ios::out: Write
- ios::app: Append
- ios::binary: Binary Mode
4. Text File Handling
**Python**:
File Handling in Python vs C++
```python
with open("example.txt", "r") as f:
for line in f:
print(line.strip())
```
**C++**:
```cpp
ifstream file("example.txt");
string line;
while (getline(file, line)) {
cout << line << endl;
}
file.close();
```
5. Comparison Table
| Feature | Python | C++ |
|---------|--------|-----|
| Simplicity | High | Medium |
| Modes | 'r', 'w', 'a' | ios::in, ios::out |
| Binary Support | 'rb', 'wb' | ios::binary |
| Error Handling | try-except | is_open(), fail() |
| Context Manager | Yes | No |
Summary
- Python is more beginner-friendly and concise.
- C++ offers greater control, ideal for performance-sensitive applications.