Skip to content

Commit 82e4f13

Browse files
committed
file handling has been added
1 parent 29b4393 commit 82e4f13

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed

07-file-handling/README.md

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
File handling is an essential concept in programming that allows you to read from and write to files on your computer.
2+
3+
## What is File Handling?
4+
5+
File handling refers to the process of performing operations on files stored in a computer’s file system. It allows you to:
6+
7+
- **Create** new files
8+
- **Read** data from existing files
9+
- **Write** data to files
10+
- **Append** new data to existing files
11+
- **Delete** files
12+
13+
These operations are fundamental for storing and retrieving data in many applications.
14+
15+
- `read_write_files.py`: A Python script that demonstrates how to perform basic file operations.
16+
17+
18+
## Basic File Operations
19+
20+
### 1. Writing to a File
21+
22+
To create a file and write data to it, use the `write_to_file` function. This function takes two arguments:
23+
24+
- `filename`: The name of the file to which data will be written.
25+
- `content`: The text data that will be written to the file.
26+
27+
When we call this function, it opens the file in write mode. If the file doesn’t exist, it creates a new one. If it does exist, the existing content is overwritten.
28+
29+
Example usage:
30+
31+
```python
32+
write_to_file('example.txt', 'This is some sample text.')
33+
```
34+

07-file-handling/read_write_files.py

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
2+
def write_to_file(filename, content):
3+
with open(filename, 'w') as file:
4+
file.write(content)
5+
print(f"Content written to {filename}")
6+
7+
def read_from_file(filename):
8+
with open(filename, 'r') as file:
9+
content = file.read()
10+
return content
11+
12+
13+
file_to_write = '07-file-handling\cricket.txt'
14+
content_to_write = 'Hello, this is a sample content for the file.'
15+
16+
17+
write_to_file(file_to_write, content_to_write)
18+
19+
content = read_from_file(file_to_write)
20+
print(f"Content read from {file_to_write}:")
21+
print(content)

0 commit comments

Comments
 (0)