-
Notifications
You must be signed in to change notification settings - Fork 0
/
Reading_and_writing_files
286 lines (215 loc) · 7.64 KB
/
Reading_and_writing_files
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
Reading And Writing Files
*************************
Filepath
--------
the file path is the path in which the file is present.
for ex: a file test.py present in the home directory's python folder has a path:
home/python/test.py
for operations done on the os, we need to import the 'os module'
import os
The path join method of os module:
----------------------------------
the join method returns a string with correct file path including the separators.
eg:
import os
print(os.path.join('home','python','test.py'))
result: home/python/test.py
creating path for a set of files in a list
------------------------------------------
import os
files=['test.py','red.pdf','disc.mp3']
for filenames in files:
print(os.path.join('home/desktop/users/python',filenames))
result:
home/desktop/users/python/test.py
home/desktop/users/python/red.pdf
home/desktop/users/python/disc.mp3
Current Working Directory
-------------------------
All the directories other than the root directories can become current working directories.
syntax: os.getcwd()
eg: import os
print(os.getcwd())
result: home/killbox
Change Directory
----------------
the change directory method of os module is used to chage the current working directory.
eg:
import os
os.chdir('home/user/killbox')
print(os.getcwd())
Note: You cannot change to a directory which does not exist.
Absolute And Relative Paths
----------------------------
Absolute path: it starts with root directory
relative path: it is relative to the current working directory
here dot(.) means this directory
and dot dot(..) means parent folder.
Creating New Folders with OS.MAKEDIRS() method
----------------------------------------------
make directory method is used to create new directories
eg:
import os
os.makedirs('home/killbox/santhu')
print('new directory is created')
Handling Absolute and relative paths
------------------------------------
-> convert relative path to absolue path or generate absolute path
Syntax: os.path.abspath(path)
eg:
import os
print(os.path.abspath('d.py'))
result: home/killbox/d.py
-> Check if a path is absolute or relaive
Syntax: os.path.isabs(path)
eg:
import os
if os.path.isabs(home/killbox/santhu)==True
print('it is absolute path')
else:
print('it is relative path')
-> Print relative path from start path to a particular path
Syntax:os.path.relpath(path,start)
eg:
import os
print(os.path.relpath('home/killbox/python','home'))
print(os.path.relpath('home/killbox/python','home/killbox/testt'))
DIRECTORY AND BASE NAME
-----------------------
Directory name: first part of the path until the last backslash---os.path.dirname(path)
base name : the last part of path after the last backslash--------os.path.basename(path)
eg: path='home/killbox/desktop/python/d.py'
print(os.path.dirname(path) # result is :'home/killbox/desktop/python'
print(os.path.basename(path) # result is :'d.py'
OS.PATH.SPLIT()
---------------
os.path.split() method of os module splits the path into dirname and base name in the form of tuples.
eg:
import os
path='home/killbox/desktop/python/d.py'
os.path.split(path)
Result: ('home/killbox/desktop/python','d.py')
the os.path.split() method never takes a path as string and returns a list of split path instead it generates tuples.
os.path.sep variable of os module stores the path without the backslash.Splitting the os.path.sep using python's split() method produces a list of the splitted elements of the path.
eg:
import os
path='home/killbox/desktop/python/d.py'
print(path.split(os.path.sep))
result: ['home', 'killbox', 'desktop', 'python', 'd.py']
Finding File Sizes and Folder Contents
--------------------------------------
Finding filesize
----------------
File sizes can be found out using
os.path.getsize(path)
eg:
import os
path='/home/killbox/python/pgm1.py'
print(str(os.path.getsize(path))+' '+'byte(s)')
result: 71 byte(s)
Finding Folder Contents
-----------------------
File contents can be generated by using os module's listdir() method.
syntax: os.listdir(path)
eg:
import os
path='/home/killbox/python/'
print(os.listdir(path))
Result: ['pgm1.py', 'catnames.py', 'collatzui.py', 'collatz.py', 'collatz.pyc']
Finding size of a folder
------------------------
Finding size of a folder and listing its contents
import os
path='/home/killbox/python/'
total=0
# listing the contents
listt=os.listdir(path)
print(listt)
#finding total size of contents
for files in listt:
total=total+os.path.getsize(os.path.join(path,files))
print(str(total)+' '+'bytes')
Checking Path Validity
----------------------
three types
->exists
------
Syntax:os.path.exists(path)
eg:
import os
path='/home/killbox/python/pgm1.py'
print(os.path.exists(path))
Result: 'True'
->is file
-------
Syntax:os.path.isfile(path)
eg:
import os
path='/home/killbox/python/pgm1.py'
print(os.path.isfile(path))
Result: 'True'
->is directory
------------
Syntax:os.path.isdir(path)
eg:
import os
path='/home/killbox/python/pgm1.py'
print(os.path.isdir(path))
Result: 'True'
NOTE:We can check whether a flash drive is mounted or not using exists() method of os module.
FILE READING AND WRITING PROCESS
--------------------------------
--> Call the open() function to return a File object.
myfile1=open('/home/killbox/python/pgm1.py')
--> Call the read() or write() method on the File object.
files can be read using the file object's read() method.
eg: content=myfile1.read()
contentbylines=myfile.readlines()
Note: by default the file will be opened in read mode. (myfile1=open('path','r') and myfile1=open(path) are same)
WRITE() and APPEND() Methods
----------------------------
write() and append() are the 2 modes in writing to a file.
Note:opening a file in write mode or append mode according to the need
Write mode: myfile1=open('path','w')
Append mode: myfile1=open('path','a')
The difference is, in write mode if the file is not present, then the file is created and if present, it will be overwritten with he new data witten to the file.
So inorder to retain the previous data and add/append new data to it, append() method of the file object is used.
--> Close the file by calling the close() method on the File object.
close() method of file object is used to close the file. once the file is closed, it cannot be accessed until the file is opened again.
myfile1.close()
SHELVE MODULE
-------------
The Shelve module can be used to store variable data to the computer harddisk for later use in the form of shelf(dbfile)
Syntax: import shelve
sfile=shelve.open('datashelf')
var={'san','dsa','nsa'}
sfile['variable']=var
sfile.close()
result: the shelf is created.
==>KEYS AND VALUES:
The shelf variable can be dictionaries and they have keys and values
--> keys: shelfobj.keys()
--> values: shelfobj.values()
NOTE: shelves return list like values but not actually lists so we have to convert them to lists
list(shelfobj.keys())
list(shelfobj.values())
eg:
import shelve
sfile=shelve.open('datashelf')
var={'san':'name','dsa':'com','nsa':'work'}
sfile['variable']=var
print(list(sfile.keys()))
print(list(sfile.values()))
sfile.close()
Saving Variables with the pprint.pformat() Function
---------------------------------------------------
pprint.pformat() method returns a string which is easily readable an syntactically correct python code which can be saved to a variable or as a python file for later use by importing the module whenever needen.
import pprint
file=[{'san':'name','19':'age'},{'athul':'name','18':'age'}]
pprint.pformat(file)
fileobj=open('xs.py','w')
fileobj.write(pprint.pformat(file))
fileobj.close()
Result: file created and data is written to the file xs.py
import xs.py
print(xs.file)