File_Handling_Python_vs_CPP
File_Handling_Python_vs_CPP
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;
}
```
**Python**:
```python
with open("data.txt", "w") as f:
f.write("Python rocks!\n")
**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
**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
Summary