-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathFileUtils.py
More file actions
731 lines (573 loc) · 17.6 KB
/
FileUtils.py
File metadata and controls
731 lines (573 loc) · 17.6 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
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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
#! /usr/bin/python
#-------------------------------------------------------------------------------
# FileUtils.py
#-------------------------------------------------------------------------------
# Example source code for the book "Real-World Instrumentation with Python"
# by J. M. Hughes, published by O'Reilly Media, December 2010,
# ISBN 978-0-596-80956-0.
#-------------------------------------------------------------------------------
""" ASCII Data File R/W Utility Classes.
Defines two classes for reading and writing ASCII data records
using text files.
The methods in this module support opening, closing, reading
and writing ASCII data in the form of single-line records. The
class ASCIIDataWrite handles data record writing, and
ASCIIDataRead handles the reading chores. The instantiated
objects maintain their own file object references, and more
than one instance of either class may be active at any one
time.
There are four record formats available, as follows:
4 fields: [sequence number] [date] [time] [data]
3 fields: [date] [time] [data]
2 fields: [sequence number] [data]
1 Field: [data]
Note that the timestamp is actually two fields: [data] and
[time]. Records with either 2 or 4 fields will contain a
sequence number. Records with only 3 fields will contain the
timestamp fields, but no sequence number. All record formats
contain the data field, and all fields are written as strings.
The [data] field is always written to a file as the string
representation of a floating point value. In other words,
integers will be written with the fractional part set to zero.
"""
import os
import TimeUtils # time and data utilities
import RetCodes as RC # shared return code definitions
import gzip
import bz2
import struct
import binascii
import time
import datetime
import ctypes
import shutil
class ASCIIDataWrite:
""" Methods for writing ASCII data records to a file.
Defines an object for writing ASCII data records to a
standard "text file". Each object is unique, and more than
one object may be in use at any one time.
"""
def __init__(self):
self.seq_num = 0
self.file_ref = None
def openOutput(self, path, file_name, reset_file=False, set_seq_num = 0):
""" Opens a file for ASCII data ouptut.
If path is not specified (an empty string is given as
the path) then the file will be opened in the current
execution directory.
If the reset_file parameter is False then file will be
opened in append mode. If True then file will be opened
in write mode and any existing data will be deleted if
the file already exists.
"""
rc = RC.NO_ERR
if len(file_name) > 0:
# create the fully qualified path name
file_path = os.path.join(path, file_name)
if reset_file:
fmode = "w"
else:
fmode = "a"
self.seq_num = set_seq_num
try:
self.file_ref = open(file_path, fmode)
except Exception, e:
rc = RC.OPEN_ERR
print "%s" % str(e)
else:
rc = RC.NO_NAME
return rc
def openCompOutput(self, path, file_name, reset_file=False):
""" Opens a file for ASCII data ouptut.
If path is not specified (an empty string is given as
the path) then the file will be opened in the current
execution directory.
If the reset_file parameter is False then file will be
opened in append mode. If True then file will be opened
in write mode and any existing data will be deleted if
the file already exists.
"""
rc = RC.NO_ERR
if len(file_name) > 0:
# create the fully qualified path name
file_path = os.path.join(path, file_name)
if reset_file:
# fmode = "w"
fmode = "wb"
else:
# fmode = "a"
fmode = "ab"
try:
# use gzip for compressed file
self.file_ref = gzip.GzipFile(file_path, fmode)
except Exception, e:
rc = RC.OPEN_ERR
print "%s" % str(e)
else:
rc = RC.NO_NAME
return rc
def openbz2Output(self, path, file_name, reset_file=False):
""" Opens a file for ASCII data ouptut.
If path is not specified (an empty string is given as
the path) then the file will be opened in the current
execution directory.
If the reset_file parameter is False then file will be
opened in append mode. If True then file will be opened
in write mode and any existing data will be deleted if
the file already exists.
"""
rc = RC.NO_ERR
if len(file_name) > 0:
# create the fully qualified path name
file_path = os.path.join(path, file_name)
if reset_file:
# fmode = "w"
fmode = "wb"
else:
# fmode = "a"
fmode = "ab"
try:
# use gzip for compressed file
self.file_ref = bz2.BZ2File(file_path, fmode)
except Exception, e:
rc = RC.OPEN_ERR
print "%s" % str(e)
else:
rc = RC.NO_NAME
return rc
def closeOutput(self):
""" Close an already opened output file.
If file is not open then an error is returned.
"""
rc = RC.NO_ERR
if self.file_ref and self.file_ref != None:
rc = closeFile(self.file_ref)
else:
rc = RC.NO_FILE
return rc
def writeData(self, dataval, use_sn=False, use_ts=False):
""" Generates a string containing a data value in ASCII.
If use_ts is False then no timestamp is applied. Otherwise
a timestamp will be obtained and applied to the output
string.
"""
rc = RC.NO_ERR
if use_sn:
# need to init the sequence number?
if self.seq_num == 0:
self.seq_num = 1
sn = "%02d " % self.seq_num
self.seq_num += 1
else:
sn = ""
if use_ts:
ts = TimeUtils.getTS() + " "
else:
ts = ""
hdr = sn + ts
# if self.file_ref is None then a file has not yet been
# opened for this instance
if self.file_ref == None:
rc = RC.NO_FILE
# do not proceed if errors encountered
if rc == RC.NO_ERR:
try:
dstr = " %f" % float(dataval)
except Exception, e:
rc = RC.INV_DATA
print "%s" % str(e)
if rc == RC.NO_ERR:
outstr = hdr + dstr + "\n"
try:
self.file_ref.write(outstr)
except Exception, e:
rc = RC.WRITE_ERR
print "%s" % str(e)
return rc
def writeStr(self, datastr,delimiter, use_sn=False, use_ts=False):
""" Generates a string containing a data value in ASCII.
If use_sn is False then no sequence number is applied. Otherwise
a timestamp will be obtained and applied to the output
string.
If use_ts is False then no timestamp is applied. Otherwise
a timestamp will be obtained and applied to the output
string.
"""
rc = RC.NO_ERR
if use_sn:
# need to init the sequence number?
if self.seq_num == 0:
self.seq_num = 1
sn = "%02d%s" % (self.seq_num,delimiter)
self.seq_num += 1
else:
sn = ""
if use_ts:
ts = TimeUtils.getTS() + delimiter
else:
ts = ""
hdr = sn + ts
# if self.file_ref is None then a file has not yet been
# opened for this instance
if self.file_ref == None:
rc = RC.NO_FILE
# do not proceed if errors encountered
if rc == RC.NO_ERR:
try:
dstr = "%s" % datastr
except Exception, e:
rc = RC.INV_DATA
print "%s" % str(e)
if rc == RC.NO_ERR:
outstr = hdr + dstr + "\n"
try:
self.file_ref.write(outstr)
except Exception, e:
rc = RC.WRITE_ERR
print "%s" % str(e)
return rc
class BinDataWrite:
""" Methods for writing ASCII data records to a file.
Defines an object for writing ASCII data records to a
standard "text file". Each object is unique, and more than
one object may be in use at any one time.
"""
def __init__(self):
self.seq_num = 0
self.file_ref = None
def openOutput(self, path, file_name, reset_file=False):
""" Opens a file for ASCII data ouptut.
If path is not specified (an empty string is given as
the path) then the file will be opened in the current
execution directory.
If the reset_file parameter is False then file will be
opened in append mode. If True then file will be opened
in write mode and any existing data will be deleted if
the file already exists.
"""
rc = RC.NO_ERR
if len(file_name) > 0:
# create the fully qualified path name
file_path = os.path.join(path, file_name)
if reset_file:
fmode = "wb"
else:
fmode = "ab"
try:
self.file_ref = open(file_path, fmode)
except Exception, e:
rc = RC.OPEN_ERR
print "%s" % str(e)
else:
rc = RC.NO_NAME
return rc
def openCompOutput(self, path, file_name, reset_file=False):
""" Opens a file for ASCII data ouptut.
If path is not specified (an empty string is given as
the path) then the file will be opened in the current
execution directory.
If the reset_file parameter is False then file will be
opened in append mode. If True then file will be opened
in write mode and any existing data will be deleted if
the file already exists.
"""
rc = RC.NO_ERR
if len(file_name) > 0:
# create the fully qualified path name
file_path = os.path.join(path, file_name)
if reset_file:
# fmode = "w"
fmode = "wb"
else:
# fmode = "a"
fmode = "ab"
try:
# use gzip for compressed file
self.file_ref = gzip.GzipFile(file_path, fmode)
except Exception, e:
rc = RC.OPEN_ERR
print "%s" % str(e)
else:
rc = RC.NO_NAME
return rc
def openbz2Output(self, path, file_name, reset_file=False):
""" Opens a file for ASCII data ouptut.
If path is not specified (an empty string is given as
the path) then the file will be opened in the current
execution directory.
If the reset_file parameter is False then file will be
opened in append mode. If True then file will be opened
in write mode and any existing data will be deleted if
the file already exists.
"""
rc = RC.NO_ERR
if len(file_name) > 0:
# create the fully qualified path name
file_path = os.path.join(path, file_name)
if reset_file:
# fmode = "w"
fmode = "wb"
else:
# fmode = "a"
fmode = "ab"
try:
# use gzip for compressed file
self.file_ref = bz2.BZ2File(file_path, fmode)
except Exception, e:
rc = RC.OPEN_ERR
print "%s" % str(e)
else:
rc = RC.NO_NAME
return rc
def closeOutput(self):
""" Close an already opened output file.
If file is not open then an error is returned.
"""
rc = RC.NO_ERR
if self.file_ref and self.file_ref != None:
rc = closeFile(self.file_ref)
else:
rc = RC.NO_FILE
return rc
def writeStr(self, datastr,delimiter, use_sn=False, use_ts=False):
""" Generates a string containing a data value in ASCII.
If use_sn is False then no sequence number is applied. Otherwise
a timestamp will be obtained and applied to the output
string.
If use_ts is False then no timestamp is applied. Otherwise
a timestamp will be obtained and applied to the output
string.
"""
rc = RC.NO_ERR
if use_sn:
# need to init the sequence number?
if self.seq_num == 0:
self.seq_num = 1
sn = "%02d%s" % (self.seq_num,delimiter)
self.seq_num += 1
else:
sn = ""
if use_ts:
ts = TimeUtils.getTS() + delimiter
else:
ts = ""
hdr = sn + ts
# if self.file_ref is None then a file has not yet been
# opened for this instance
if self.file_ref == None:
rc = RC.NO_FILE
# do not proceed if errors encountered
if rc == RC.NO_ERR:
try:
dstr = "%s" % datastr
except Exception, e:
rc = RC.INV_DATA
print "%s" % str(e)
if rc == RC.NO_ERR:
outstr = hdr + dstr + "\n"
l = len(outstr)
recstr = str(l) + 's'
srec = struct.pack(recstr, outstr)
try:
self.file_ref.write(srec)
except Exception, e:
rc = RC.WRITE_ERR
print "%s" % str(e)
return rc
class ASCIIDataRead:
""" Defines an object for reading ASCII data records from a
standard text file. Each object is unique, and more than
one object may be in use at any one time.
"""
def __init__(self):
self.file_ref = None
def openInput(self, path, file_name):
""" Opens a file for ASCII data input.
If path is not specified (an empty string is given as
the path) then the function will attempt to open the
named file in the current execution directory.
"""
rc = RC.NO_ERR
# if path is none, assume file is in local directory
if path == None:
path = './'
# create the fully qualified path name
file_path = os.path.join(path, file_name)
try:
self.file_ref = open(file_path, "r")
except Exception, e:
rc = RC.OPEN_ERR
self.file_ref = None
return rc
def closeInput(self):
""" Close an already opened input file.
If file is not already open then an error is returned.
Calls the module function closeFile() to do the actual
close.
"""
rc = RC.NO_ERR
if self.file_ref and self.file_ref != None:
rc = closeFile(self.file_ref)
else:
rc = RC.NO_FILE
return rc
def readDataRecord(self):
""" Read a complete record string and return it as-is.
Reads one record at a time and returns the entire record
string as-is from the file. An EOF returns an empty
record string.
Return is a 2-tuple consisting of a return code and the
record string.
"""
rc = RC.NO_ERR
# verify that there is a valid file to read from
if self.file_ref != None:
# fetch a line from the file
try:
record = self.file_ref.readline()
except Exception, e:
record = ""
rc = RC.READ_ERR
else:
record = ""
rc = RC.NO_FILE
return rc, record
def readDataFields(self):
""" Read fields from a record in an ASCII data file.
Reads one record at a time, and returns each record
as a list object with one list element per field. An
EOF returns an empty list.
The data for each field is converted from strings to
the appropriate data type based on the number of fields
in the record.
Returns a 2-tuple consisting of a return code and the
fields list object.
"""
rc = RC.NO_ERR
readflds = []
retflds = []
# fetch record string from file
rc, recstr = self.readDataRecord()
# split record into component elements
if rc == RC.NO_ERR:
if len(recstr) > 0:
readflds = recstr.split(';')
# Use a try-catch in case data is an invalid type
# for given conversion to int or float.
try:
if len(readflds) == 4:
retflds.append(int(readflds[0]))
retflds.append(int(readflds[1]))
retflds.append(readflds[2])
retflds.append(float(readflds[3]))
elif len(readflds) == 3:
retflds.append(int(readflds[0]))
retflds.append(readflds[1])
retflds.append(float(readflds[2]))
elif len(readflds) == 2:
retflds.append(int(readflds[0]))
retflds.append(float(readflds[1]))
elif len(readflds) == 1:
retflds.append(float(readflds[0]))
else:
rc = RC.INV_FORMAT
except Exception, e:
print str(e)
retflds = []
rc = RC.INV_DATA
else:
rc = RC.NO_DATA
return rc, retflds
def getData(self):
""" Returns just the data portion of a record.
Returns a 2-tuple consisting of the return code and the
data value.
A record should always have a data field. This method
returns just the data field, and nothing else, as a
floating point value. If the data field does not exist
or if an error occurs retrieving a record, then it will
return None.
"""
retdata = None
rc, infields = self.readDataFields()
if rc == RC.NO_ERR:
# assume that readDataFields() has done its job correctly
# and we have a valid number of fields to work with.
if len(infields) == 4:
retdata = float(infields[3])
elif len(infields) == 3:
retdata = float(infields[2])
elif len(infields) == 2:
retdata = float(infields[1])
elif len(infields) == 1:
retdata = float(infields[0])
return rc, retdata
# Module functions
def closeFile(file_id):
""" Close an already opened input or output file.
file_id is a refernce to a Python file object.
"""
rc = RC.NO_ERR
try:
file_id.close()
except Exception, e:
rc = RC.INV_FILE
print "%s" % str(e)
return rc
def compressFile (inFile, outFile):
"""
###############################################################################
# compress inFile with gzip and write it to outFile
###############################################################################
"""
f_in = open(inFile, 'rb')
f_out = gzip.open(outFile, 'wb')
f_out.writelines(f_in)
f_out.close()
f_in.close()
if __name__ == "__main__":
fout = ASCIIDataWrite()
fin = ASCIIDataRead()
fout.openOutput("./", "futest.dat")
fout.writeData(2.5, use_ts=True)
fout.writeData(2.6, use_ts=True)
fout.writeData(2.7, use_ts=True)
fout.writeData(2.8, use_ts=True)
fout.writeData(2.9, use_ts=True)
fout.writeData(3.0, use_ts=True)
fout.closeOutput()
fin.openInput("./","futest.dat")
print "Read Records"
print "%d %s" % fin.readDataRecord(),
print "%d %s" % fin.readDataRecord(),
print "%d %s" % fin.readDataRecord(),
print "%d %s" % fin.readDataRecord(),
print "%d %s" % fin.readDataRecord(),
print "%d %s" % fin.readDataRecord(),
fin.closeInput()
fin.openInput("./","futest.dat")
print "Read Fields"
print "%d %s" % fin.readDataFields()
print "%d %s" % fin.readDataFields()
print "%d %s" % fin.readDataFields()
print "%d %s" % fin.readDataFields()
print "%d %s" % fin.readDataFields()
print "%d %s" % fin.readDataFields()
fin.closeInput()
def purgeDir(folder, sub = False):
"""
###############################################################################
# deletes all files in directory
# if 'sub' is True, sub directories are deleted as well
###############################################################################
"""
for the_file in os.listdir(folder):
file_path = os.path.join(folder, the_file)
try:
if os.path.isfile(file_path):
os.unlink(file_path)
# if there is subdirectories to purge...
elif sub:
if os.path.isdir(file_path): shutil.rmtree(file_path)
except Exception as e:
print(e)