-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path20.4_Files - Read, Write, Delete & Appending to a file.py
More file actions
77 lines (55 loc) · 2.34 KB
/
20.4_Files - Read, Write, Delete & Appending to a file.py
File metadata and controls
77 lines (55 loc) · 2.34 KB
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
''''
1. Writing and Appending to a file :-
i) 'w' mode -
w stands for write. After opening or creating a files, a function , f.write() is used to insert text int ht he files. The tet is written to the write m ode of the opening file that it overrides the existing data in the file. For a newly created file, it does no harm, but in case of already exisiting files, the previous data is lost as f.write() overrides it.
ii) 'a' mode -
a stands for append mode. 'Append' meand adding more content at the end of the existing file unlike 'w' mode which means adding something anywhere to the file. The same function, f.write() is used to add text to the file in append mode.
iii) 'r+' mode -
Reading and Writing a file simultaneously. Well, r+ mode is more of a combination of "reading" and "append" than read and write. By opening a file in this mode, we can print the existing content on to the screen by printing f.read() function and adding or appending text to it using f.write() function.
2) Deleting a File :-
To delete a file, we must import the OS module, and run it's 'os.remove()' function.
eg:-
import os
os.remove("testfile.txt")
NOTE :- If you are writing in append mode, start your text by putting a blank space or newline character (\n) else the compiler will start the line from the last word or full stop without any blank space because the curser in case of append mode is placed right after the last character.
'''
#Examples :-
'''
# 1. Write Mode
p = open("FileAppend.txt", "w")
a = p.write("This is a file created for the 22th chapter\n")
print(a) #gives 44
p.close()
'''
'''
# 2. Read Mode
f = open("FileAppend.txt", "a")
a = f.write("Pritam is a good boy\n")
print(a) #gives 21
f.close()
O/P
'''
'''
# 3. Read + Write mode
x = open("FileAppend.txt", "r+")
print(x.read())
x.write("This will append to the end of the content of the file")
'''
'''
Final output in the 'FileAppend.txt'
This is a file created for the 22th chapter
Pritam is a good boy
This will change the content of the file
'''
# 4. Deleting a file
#Creating a random file named 'newfile.txt'
'''
new1 = open("newfile.txt", "r+")
new1.write("This is the new file which will be deleted using OS module.")
new1.close()
'''
#Later on deleting the same file named 'newfile.txt' using os module.
'''
import os
os.remove("newfile.txt")
'''