-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfile_handling_1.py
More file actions
70 lines (51 loc) · 1.78 KB
/
file_handling_1.py
File metadata and controls
70 lines (51 loc) · 1.78 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
from os import read
import os
### checkout python docs for more https://docs.python.org/3/library/filesys.html
### file = open('filename' , 'mode')
"""
modes = r (read only)
r+ (read and write)
w (write) ## the W mode overwrites the entire file.....so beware
a (append) ## append mode appends text at the end of file
x (create)
t (text)
b (binary)
"""
# file reading
file = open('trial.txt' , 'r+')
for each in file:
print(each)
print (file.read())
# file writing
file.write("this is the write function\n")
file.write("this lets us write to the file\n")
file.close # the close function lets us close all the resources in use
## Append mode
file = open('trial.txt','a')
file.write("writing this in append mode\n")
file.close
## using write with with()
# the advantage of using with is that it ensures the file is closed
# after nested block of code is ran
with open('trial.txt','r+') as file:
text = file.read()
file.write("writing from within with()\n")
## creating a file using x mode
file2 = open('newfile','x') ## creates the file ...returns error if the file already exists
os.remove("newfile") ## this removes the file
## readline()
file3 = open('trial.txt')
print(file3.readline())
print(file3.readline()) ## this would print the first two lines of the file
## create a file , add a line and a string , read them , split the string and store it in a list , delete the file by checking if it exists atfirst
file4 = open("myfile","x")
file4 = open("myfile","r+")
file4.write("this is the line\n")
file4.write("apple , banana , cherry , mango")
content = file4.read()
print(content) #TODO debug here...
file4.close()
if os.path.exists("myfile"):
os.remove("myfile")
else:
print("the file doesnt exist\n")