-
Notifications
You must be signed in to change notification settings - Fork 26
/
Project1:Manipulating Files and Folders
100 lines (76 loc) · 2.36 KB
/
Project1:Manipulating Files and Folders
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
93
94
95
96
97
98
99
100
#create a file
"""
steps->
#open a file
#give name+extension
#click enter """
fo=open("D:\\exm.txt",'w')
fo.write("Hello!!!")
#to write multiple lines
# create a list of item.
line_list=["How are you? \n","How is the weather there? \n"]
fo.writelines(line_list)
#update a file
"""
steps->
To update a file, we use same steps
but open the file in appned mode. """
fo=open("D:\\exm.txt",'a')
fo.write("Hello all. Welcome to ISB.")
#to update with multiple lines
# create a list of item.
line_list=["It is really hot in Kolkata.\n","BTW how is your preparation for ISB going on\n","Are you attending the warm up session?\n"]
fo.writelines(line_list)
# use case1
# one file has data for starting 15 days of a month
# other file has data for next 15 days of a month
# you want to update the data in the older file.
#open the first file in append mode
ff=open("D:\\example.txt",'a')
#open the second file in read mode
sf=open("D:\\exm.txt",'r')
#read data from second file
info=sf.read()
##append the info data in the first file
ff.write(info)
#close both the files
ff.close()
sf.close()
# moving a file
#steps->
# change the location of a file.
#importing useful libray
import os
import shutil
# new directory formation-> os.mkdir("new_directiry_path")
os.mkdir("D:\\Mani\\")
shutil.move("D:\\ABC","D:\\Mani\\")
#to copy a file or folder
shutil.copy("D:\\4th Semester Result.pdf","D:\\Mani\\4th Semester Result.pdf")
# to copy multiple files.
#steps
# for every file , copy it.
file_list=["D:\\4th Semester Result.pdf","D:\\5th Semester Result.pdf","D:\\6th Semester Result.pdf"]
for file in file_list:
shutil.copy(file,"D:\\Mani\\")
# to rename a file
#steps->
# change the location from old to new
os.rename("D:\\1st Sem_res.jpeg","D:\\1st Semester Result.jpeg")
# use case 2
# for 2nd Sem_res.jpeg and 3rd Sem_res.jpeg rename it to 2nd Semester Result.jpeg & 3rd Semester Result.jpeg
# we need to make
# Sem_res.jpeg-> Semester Result.jpeg
# that means we need to make
# D:\\2nd Sem_res.jpeg->D:\\2nd Semester Result.jpeg
#creating a list of the files
re_files=["D:\\2nd Sem_res.jpeg","D:\\3rd Sem_res.jpeg"]
for i in re_files:
j=i.split(" ")#splitting across a space
new_path=j[0]+' Semester Result.jpeg' # concatenating to get the new path
#print(new_path)
os.rename(i,new_path)#renaming
#to delete a file
#steps->
#make the location available.
os.remove("D:\\Mani\\ABC")