Repository navigation
Expand file tree
/
Copy pathfilehandling.py
More file actions
92 lines (61 loc) · 1.63 KB
/
Copy pathfilehandling.py
File metadata and controls
92 lines (61 loc) · 1.63 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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#learning file handling
#Open file
file = open('example.txt','w')
#write file
f = open("example.txt", "w")
f.write("Hello, Python!\n")
f.write("This is file handling step by step.")
f.close()
f = open("example.txt", "a")
f.write("\nThis line is appended.")
f.close()
#read file
f = open("example.txt", "r")
content = f.read()
print(content)
f.close()
#reading methods
# f.readline() # reads one line
# f.readlines() # reads all lines into a list
# with
with open("example.txt", "r") as f:
for line in f:
print(line.strip())
#checking file is exist or not
import os
if os.path.exists("example.txt"):
print("File exists")
else:
print("File not found")
#deleting
import os
if os.path.exists("myfile.txt"):
os.remove("myfile.txt")
print("File deleted successfully")
else:
print("No file found")
#copy image
# with open("image.jpg", "rb") as f: # read binary
# data = f.read()
# with open("copy.jpg", "wb") as f: # write binary
# f.write(data)
#working with directories
import os
# create a folder named "myfolder"
os.mkdir("myfolder")
print("Folder created successfully")
import os
# create "parent/child" directories at once
os.makedirs("parent/child", exist_ok=True)
print("Nested folders created successfully")
import os
print(os.listdir(".")) # list files in current directory
print(os.listdir("parent")) # list inside "parent" folder
import os
# remove empty folder
os.rmdir("myfolder")
print("Folder deleted successfully")
import shutil
# remove entire folder with its contents
shutil.rmtree("parent")
print("Folder and all files deleted successfully")