-
-
Notifications
You must be signed in to change notification settings - Fork 522
/
file_handling.py
60 lines (42 loc) · 1.66 KB
/
file_handling.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
"""
File handling is a fundamental concept in Python that involves
opening, reading, writing, and appending to files. This module
demonstrates the basics of file handling in Python.
Python provides various ways to work with files. We can use the
builtin 'open' function to open files in different modes like
reading ('r'), writing ('w'), and appending ('a').
"""
import os
_TARGET_FILE = "sample.txt"
def read_file(filename):
"""Read content from existing file."""
with open(filename, "r") as file:
content = file.read()
return content
def write_file(filename, content):
"""Write content to new file."""
with open(filename, "w") as file:
file.write(content)
return f"Content written to '{filename}'."
def append_file(filename, content):
"""Append content to existing file."""
with open(filename, "a") as file:
file.write(content)
return f"Content appended to '{filename}'."
def delete_file(filename):
"""Delete content of existing file."""
os.remove(filename)
return f"'{filename}' has been deleted."
def main():
result = write_file(_TARGET_FILE, "This is a test.")
assert result == f"Content written to '{_TARGET_FILE}'."
content = read_file(_TARGET_FILE)
assert content == "This is a test."
append_result = append_file(_TARGET_FILE, "\nThis is an appended line.")
assert append_result == f"Content appended to '{_TARGET_FILE}'."
content = read_file(_TARGET_FILE)
assert content == "This is a test.\nThis is an appended line."
delete_result = delete_file(_TARGET_FILE)
assert delete_result == f"'{_TARGET_FILE}' has been deleted."
if __name__ == "__main__":
main()