-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfileOperations.py
More file actions
766 lines (611 loc) · 38.7 KB
/
Copy pathfileOperations.py
File metadata and controls
766 lines (611 loc) · 38.7 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
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
from cmath import e
from logging import exception
from sys import flags
import time
import re
class fileOperations:
"""
FSIF - Find String Inside a File
"""
def __init__(self):
filePath = None
searchString = None
def fsif_and_number_of_occurences(self,filePath,searchString,caseSensitive):
"""
This Object finds the total occurence of the provided string inside the file using builtin count() method.
It returns a list containing dict items such as execution time and total occurence.
Example usage:
| fsif_and_number_of_occurences | filePath = <String><Path> | searchString = <String> | caseSensitive = <Boolean>
"""
try:
fsifList = []
startTime = time.time()
with open(filePath,"r",encoding="utf8") as file:
fileRead = file.read()
searchStringLower = searchString.lower()
numOfOccurenceSensitive = fileRead.count(searchString)
numOfOccurenceInsesitive = fileRead.lower().count(searchStringLower)
if caseSensitive:
fsifList.insert(0,{f'Total Occurence of "{searchString}"':numOfOccurenceSensitive})
else:
fsifList.insert(0,{f'Total Occurence of "{searchStringLower}"':numOfOccurenceInsesitive})
file.close()
endTime = time.time()
fsifList.insert(0,{'Execution Time in seconds' : "{:.2f}".format(endTime - startTime)})
return fsifList
except Exception as e:
return e
def fsif_and_first_n_occurences(self,filePath,searchString,caseSensitive,n):
"""
This Object finds first n occurence of the provided string inside the file using builtin count() method
and by maintaining a counter based on input n. It returns a list containing dict items such as execution
time, total occurence and first n occurences.
Example usage:
| fsif_and_first_n_occurences | filePath = <String><Path> | searchString = <String> | caseSensitive = <Boolean> | n = <int>
"""
try:
fsifList = []
startTime = time.time()
with open(filePath,"r",encoding="utf8") as file:
totalOccurence = 0
lines = file.readlines()
for line in lines:
count = 0
if caseSensitive:
if searchString in line:
count = line.count(searchString)
totalOccurence = totalOccurence + count
fsifDict = {'Line number':lines.index(line),'Line':line,'Count':count}
if n > 0:
fsifList.append(fsifDict)
n = n - count
else:
searchStringLower = searchString.lower()
lineLower = line.lower()
if searchStringLower in lineLower:
count = lineLower.count(searchStringLower)
totalOccurence = totalOccurence + count
fsifDict = {'Line number':lines.index(line),'Line':line,'Count':count}
if n > 0:
fsifList.append(fsifDict)
n = n - count
file.close()
endTime = time.time()
fsifList.insert(0,{'Execution Time in seconds' : "{:.2f}".format(endTime - startTime)})
fsifList.insert(1,{f'Total Occurence of "{searchString}"':totalOccurence})
return fsifList
except Exception as e:
return e
def fsif_and_last_n_occurences(self,filePath,searchString,caseSensitive,n):
"""
This Object finds last n occurence of the provided string inside the file using builtin count() method
and by maintaining a counter based on input n. It returns a list containing dict items such as execution
time, total occurence and last n occurences.
Example usage:
| fsif_and_last_n_occurences | filePath = <String><Path> | searchString = <String> | caseSensitive = <Boolean> | n = <int>
"""
try:
fsifList = []
lastFsifList = []
startTime = time.time()
with open(filePath,"r",encoding="utf8") as file:
totalOccurence = 0
lines = file.readlines()
for line in lines:
count = 0
if caseSensitive:
if searchString in line:
count = line.count(searchString)
totalOccurence = totalOccurence + count
fsifDict = {'Line number':lines.index(line),'Line':line,'Count':count}
fsifList.append(fsifDict)
else:
searchStringLower = searchString.lower()
lineLower = line.lower()
if searchStringLower in lineLower:
count = lineLower.count(searchStringLower)
totalOccurence = totalOccurence + count
fsifDict = {'Line number':lines.index(line),'Line':line,'Count':count}
fsifList.append(fsifDict)
for item in fsifList[::-1]:
if n > 0:
lastFsifList.append(item)
n = n - item['Count']
file.close()
endTime = time.time()
lastFsifList.insert(0,{'Execution Time in seconds' : "{:.2f}".format(endTime - startTime)})
lastFsifList.insert(1,{f'Total Occurence of "{searchString}"':totalOccurence})
return lastFsifList
except Exception as e:
return e
def fsif_and_replace_all_occurences(self,filePath,searchString,replaceString,caseSensitive):
"""
This Object finds all occurences of the provided string inside the file using re.sub() method.
It returns a list containing dict items such as execution time and total occurence replacement.
Example usage:
| fsif_and_replace_all_occurences | filePath = <String><Path> | searchString = <String> | replaceString = <String> | caseSensitive = <Boolean> |
"""
try:
fsifList = []
startTime = time.time()
with open(filePath,"r+",encoding="utf8") as file:
fileContent = file.read()
numOfOccurenceSensitive = fileContent.count(searchString)
numOfOccurenceInsesitive = fileContent.lower().count(searchStringLower)
if caseSensitive:
replacedFileContent = re.sub(searchString, replaceString, fileContent)
file.seek(0)
file.write(replacedFileContent)
file.truncate()
if replacedFileContent != fileContent:
fsifList.insert(0,{f"Found occurence of {searchString} and Replace of all {numOfOccurenceSensitive} occurence is success"})
else:
searchStringLower = searchString.lower()
replacedFileContent = re.sub(searchStringLower, replaceString, fileContent.lower())
file.seek(0)
file.write(replacedFileContent)
file.truncate()
if replacedFileContent != fileContent:
fsifList.insert(0,{f"Found occurence of {searchString} and Replace of all {numOfOccurenceInsesitive} occurence is success"})
file.close()
endTime = time.time()
if len(fsifList)==0:
fsifList.insert(0,{f"{searchString} - not found in file."})
fsifList.insert(0,{'Execution Time in seconds' : "{:.2f}".format(endTime - startTime)})
return fsifList
except Exception as e:
return e
def fsif_and_replace_occurence_at_line(self,filePath,searchString,replaceString,occurenceNumber,lineNumber,caseSensitive):
"""
This Object finds nth occurence of the provided string at a line inside the file using builtin split() and join() methods.
It returns a list containing dict items such as execution time and occurence replacement.
Example usage:
| fsif_and_replace_occurence_at_line | filePath = <String><Path> | searchString = <String> | replaceString = <String> | occurenceNumber = <int> | lineNumber = <int> | caseSensitive = <Boolean> |
"""
try:
fsifList = []
startTime = time.time()
with open(filePath,"r",encoding="utf8") as file:
lines = file.readlines()
if lineNumber <= len(lines):
oldLineContent = lines[lineNumber-1]
if caseSensitive:
arr=lines[lineNumber-1].split(searchString)
part1=searchString.join(arr[:occurenceNumber])
part2=searchString.join(arr[occurenceNumber:])
lines[lineNumber-1] = part1 + replaceString + part2
with open(filePath,"w",encoding="utf8") as file:
for line in lines:
file.write(line)
file.close()
#Compare with old line, to confirm the replacement
with open(filePath,"r",encoding="utf8") as file:
if file.readlines()[lineNumber-1] != oldLineContent:
fsifList.insert(0,{f"Found occurence of {searchString} at line number {lineNumber} and Replace of nth occurence is success"})
else:
arr=re.split(searchString,lines[lineNumber-1],flags=re.IGNORECASE)
part1=searchString.join(arr[:occurenceNumber])
part2=searchString.join(arr[occurenceNumber:])
lines[lineNumber-1] = part1 + replaceString + part2
with open(filePath,"w",encoding="utf8") as file:
for line in lines:
file.write(line)
file.close()
#Compare with old line, to confirm the replacement
with open(filePath,"r",encoding="utf8") as file:
if file.readlines()[lineNumber-1] != oldLineContent:
fsifList.insert(0,{f"Found occurence of {searchString} at line number {lineNumber} and Replace of nth occurence is success"})
else:
return f"File has only {len(lines)} lines. Please check the line number."
file.close()
endTime = time.time()
if len(fsifList)==0:
fsifList.insert(0,{f"{searchString} - not found in file or nth occurence does not exist"})
fsifList.insert(0,{'Execution Time in seconds' : "{:.2f}".format(endTime - startTime)})
return fsifList
except Exception as e:
return e
def fsif_and_number_of_occurences_and_nth_line(self,filePath,searchString,occurenceNumber,caseSensitive):
"""
This Object finds the nth occurence of the provided string inside the file using builtin count() methods.
It returns a list containing dict items such as execution time, line number of nth occurence, the corresponding line contents
and total occurence.
Example usage:
| fsif_and_number_of_occurences_and_nth_line | filePath = <String><Path> | searchString = <String> | occurenceNumber = <int> | caseSensitive = <Boolean> |
"""
try:
fsifList = []
startTime = time.time()
with open(filePath,"r",encoding="utf8") as fileForTotalCount:
fileRead = fileForTotalCount.read()
searchStringLower = searchString.lower()
numOfOccurenceSensitive = fileRead.count(searchString)
numOfOccurenceInsesitive = fileRead.lower().count(searchStringLower)
if caseSensitive:
fsifList.insert(0,{f'Total Occurence of "{searchString}"':numOfOccurenceSensitive})
else:
fsifList.insert(0,{f'Total Occurence of "{searchStringLower}"':numOfOccurenceInsesitive})
with open(filePath,"r",encoding="utf8") as file:
lines = file.readlines()
totalOccurence = 0
for line in lines:
count = 0
if caseSensitive:
if searchString in line:
count = line.count(searchString)
if (count+totalOccurence) >= occurenceNumber:
fsifList.insert(0,{f"Found nth occurence of {searchString} at line number {lines.index(line)+1}"})
fsifList.insert(1,{f"Content : {line}"})
break
else:
totalOccurence = totalOccurence + count
else:
searchStringLower = searchString.lower()
lineLower = line.lower()
if searchStringLower in lineLower:
count = lineLower.count(searchStringLower)
if (count+totalOccurence) >= occurenceNumber:
fsifList.insert(0,{f"Found nth occurence of {searchString} at line number {lines.index(line)+1}"})
fsifList.insert(1,{f"Content : {line}"})
break
else:
totalOccurence = totalOccurence + count
file.close()
endTime = time.time()
if len(fsifList)==0:
fsifList.insert(0,{f"{searchString} - not found in file or nth occurence does not exist"})
fsifList.insert(0,{'Execution Time in seconds' : "{:.2f}".format(endTime - startTime)})
return fsifList
except Exception as e:
return e
def fsif_and_print_store_xy_lines(self,filePath,searchString,xLinesCount,yLinesCount,caseSensitive):
"""
This Object finds the occurence of the provided string inside the file using builtin methods. Each line is iterated
through readlines() mehtod and when string is found, x<int> lines above and y<int> lines below the occurence are stored
in a list. It then returns a list containing dict items such as execution time, line number of nth occurence, contents of
x lines above and contents of y lines below.
Example usage:
| fsif_and_print_store_xy_lines | filePath = <String><Path> | searchString = <String> | xLinesCount = <int> | yLinesCount = <int> | caseSensitive = <Boolean> |
"""
try:
fsifList = []
xLines = []
yLines = []
startTime = time.time()
with open(filePath,"r",encoding="utf8") as file:
lines = file.readlines()
for line in lines:
if caseSensitive:
if searchString in line:
lineOfOccurence = lines.index(line)+1
#String[:start before which index][start index][upto index]
xLines.append(lines[:lineOfOccurence][(lineOfOccurence-xLinesCount)-1:lineOfOccurence-1])
yLines.append(lines[lineOfOccurence:][(yLinesCount-1)::-1][::-1])
fsifList.insert(0,{f"Found occurence of {searchString} at line number {lines.index(line)+1}"})
fsifList.insert(1,{f"x lines above: {xLines}"})
fsifList.insert(2,{f"y lines below: {yLines}"})
break
else:
searchStringLower = searchString.lower()
lineLower = line.lower()
if searchStringLower in lineLower:
lineOfOccurence = lines.index(line)+1
#String[:start before which index][start index][upto index]
xLines.append(lines[:lineOfOccurence][(lineOfOccurence-xLinesCount)-1:lineOfOccurence-1])
yLines.append(lines[lineOfOccurence:][(yLinesCount-1)::-1][::-1])
fsifList.insert(0,{f"Found occurence of {searchString} at line number {lines.index(line)+1}"})
fsifList.insert(1,{f"x lines above: {xLines}"})
fsifList.insert(2,{f"y lines below: {yLines}"})
break
file.close()
endTime = time.time()
if len(fsifList)==0:
fsifList.insert(0,{f"{searchString} - not found in file."})
fsifList.insert(0,{'Execution Time in seconds' : "{:.2f}".format(endTime - startTime)})
return fsifList
except Exception as e:
return e
def fsif_and_replace_above_line_match(self,filePath,searchString,replaceString,aboveLineContent,caseSensitive):
"""
This Object finds the occurence of the provided string inside the file using builtin methods and replaces the search string
only if the contents of the line above the occurence contains the aboveLineContent<String>. It then returns a list containing
dict items such as execution time and replace status.
Example usage:
| fsif_and_replace_above_line_match | filePath = <String><Path> | searchString = <String> | replaceString = <String> | aboveLineContent = <String> | caseSensitive = <Boolean> |
"""
try:
fsifList = []
startTime = time.time()
#occurenceNumber is 1 since we are replacing the first occurence of search element that we find in the line
occurenceNumber = 1
with open(filePath,"r",encoding="utf8") as file:
lines = file.readlines()
for line in lines:
if caseSensitive:
if searchString in line:
if aboveLineContent in lines[lines.index(line)-1]:
arr=lines[lines.index(line)].split(searchString)
part1=searchString.join(arr[:occurenceNumber])
part2=searchString.join(arr[occurenceNumber:])
lines[lines.index(line)] = part1 + replaceString + part2
with open(filePath,"w",encoding="utf8") as file:
for line in lines:
file.write(line)
file.close()
fsifList.insert(0,{f"Found occurence of {searchString} and Replace Success"})
break
else:
searchStringLower = searchString.lower()
lineLower = line.lower()
aboveLineContentLower = aboveLineContent.lower()
if searchStringLower in lineLower:
if aboveLineContentLower in lines[lines.index(line)-1].lower():
arr=re.split(searchString,lines[lines.index(line)],flags=re.IGNORECASE)
part1=searchString.join(arr[:occurenceNumber])
part2=searchString.join(arr[occurenceNumber:])
lines[lines.index(line)] = part1 + replaceString + part2
with open(filePath,"w",encoding="utf8") as file:
for line in lines:
file.write(line)
file.close()
fsifList.insert(0,{f"Found occurence of {searchString} and Replace Success"})
break
file.close()
endTime = time.time()
if len(fsifList)==0:
fsifList.insert(0,{f"{searchString} - not found in file or the line above does not match the given data."})
fsifList.insert(0,{'Execution Time in seconds' : "{:.2f}".format(endTime - startTime)})
return fsifList
except Exception as e:
return e
def fsif_and_replace_below_line_match(self,filePath,searchString,replaceString,belowLineContent,caseSensitive):
"""
This Object finds the occurence of the provided string inside the file using builtin methods and replaces the search string
only if the contents of the line below the occurence contains the belowLineContent<String>. It then returns a list containing
dict items such as execution time and replace status.
Example usage:
| fsif_and_replace_below_line_match | filePath = <String><Path> | searchString = <String> | replaceString = <String> | belowLineContent = <String> | caseSensitive = <Boolean> |
"""
try:
fsifList = []
startTime = time.time()
#occurenceNumber is 1 since we are replacing the first occurence of search element that we find in the line
occurenceNumber = 1
with open(filePath,"r",encoding="utf8") as file:
lines = file.readlines()
for line in lines:
if caseSensitive:
if searchString in line:
if belowLineContent in lines[lines.index(line)+1]:
arr=lines[lines.index(line)].split(searchString)
part1=searchString.join(arr[:occurenceNumber])
part2=searchString.join(arr[occurenceNumber:])
lines[lines.index(line)] = part1 + replaceString + part2
with open(filePath,"w",encoding="utf8") as file:
for line in lines:
file.write(line)
file.close()
fsifList.insert(0,{f"Found occurence of {searchString} and Replace Success"})
break
else:
searchStringLower = searchString.lower()
lineLower = line.lower()
belowLineContentLower = belowLineContent.lower()
if searchStringLower in lineLower:
if belowLineContentLower in lines[lines.index(line)+1].lower():
arr=re.split(searchString,lines[lines.index(line)],flags=re.IGNORECASE)
part1=searchString.join(arr[:occurenceNumber])
part2=searchString.join(arr[occurenceNumber:])
lines[lines.index(line)] = part1 + replaceString + part2
with open(filePath,"w",encoding="utf8") as file:
for line in lines:
file.write(line)
file.close()
fsifList.insert(0,{f"Found occurence of {searchString} and Replace Success"})
break
file.close()
endTime = time.time()
if len(fsifList)==0:
fsifList.insert(0,{f"{searchString} - not found in file or the line below does not match the given data."})
fsifList.insert(0,{'Execution Time in seconds' : "{:.2f}".format(endTime - startTime)})
return fsifList
except Exception as e:
return e
def fsif_and_replace_n_and_m_line_match(self,filePath,searchString,replaceString,aboveLineContent,belowLineContent,caseSensitive):
"""
This Object finds the occurence of the provided string inside the file using builtin methods and replaces the search string
only if the contents of the line above and below the occurence contains the aboveLineContent<String> and belowLineContent<String>.
It then returns a list containing dict items such as execution time and replace status.
Example usage:
| fsif_and_replace_n_and_m_line_match | filePath = <String><Path> | searchString = <String> | replaceString = <String> | aboveLineContent = <String> | belowLineContent = <String> | caseSensitive = <Boolean> |
"""
try:
fsifList = []
startTime = time.time()
#occurenceNumber is 1 since we are replacing the first occurence of search element that we find in the line
occurenceNumber = 1
with open(filePath,"r",encoding="utf8") as file:
lines = file.readlines()
for line in lines:
if caseSensitive:
if searchString in line:
if aboveLineContent in lines[lines.index(line)-1] and belowLineContent in lines[lines.index(line)+1]:
arr=lines[lines.index(line)].split(searchString)
part1=searchString.join(arr[:occurenceNumber])
part2=searchString.join(arr[occurenceNumber:])
lines[lines.index(line)] = part1 + replaceString + part2
with open(filePath,"w",encoding="utf8") as file:
for line in lines:
file.write(line)
file.close()
fsifList.insert(0,{f"Found occurence of {searchString} and Replace Success"})
break
else:
searchStringLower = searchString.lower()
lineLower = line.lower()
belowLineContentLower = belowLineContent.lower()
aboveLineContentLower = aboveLineContent.lower()
if searchStringLower in lineLower:
if aboveLineContentLower in lines[lines.index(line)-1].lower() and belowLineContentLower in lines[lines.index(line)+1].lower():
arr=re.split(searchString,lines[lines.index(line)],flags=re.IGNORECASE)
part1=searchString.join(arr[:occurenceNumber])
part2=searchString.join(arr[occurenceNumber:])
lines[lines.index(line)] = part1 + replaceString + part2
with open(filePath,"w",encoding="utf8") as file:
for line in lines:
file.write(line)
file.close()
fsifList.insert(0,{f"Found occurence of {searchString} and Replace Success"})
break
file.close()
endTime = time.time()
if len(fsifList)==0:
fsifList.insert(0,{f"{searchString} - not found in file or the line above or below does not match the given data."})
fsifList.insert(0,{'Execution Time in seconds' : "{:.2f}".format(endTime - startTime)})
return fsifList
except Exception as e:
return e
def fsif_and_replace_nth_above_line_match(self,filePath,lineNumber,searchString,replaceString,aboveLineContent,caseSensitive):
"""
This Object finds the occurence of the provided string at a line number inside the file using builtin methods and replaces the occurence
only if the contents of the line above contains the aboveLineContent<String>. It then returns a list containing dict items such as execution
time, occurence line number and replace status.
Example usage:
| fsif_and_replace_nth_above_line_match | filePath = <String><Path> | lineNumber = <int> | searchString = <String> | replaceString = <String> | aboveLineContent = <String> | caseSensitive = <Boolean> |
"""
try:
fsifList = []
startTime = time.time()
#occurenceNumber is 1 since we are replacing the first occurence of search element that we find in the line
occurenceNumber = 1
with open(filePath,"r",encoding="utf8") as file:
lines = file.readlines()
if lineNumber <= len(lines):
oldLineContent = lines[lineNumber-1]
if caseSensitive:
if aboveLineContent in lines[lineNumber-2]:
if searchString in lines[lineNumber-1]:
arr=lines[lineNumber-1].split(searchString)
part1=searchString.join(arr[:occurenceNumber])
part2=searchString.join(arr[occurenceNumber:])
lines[lineNumber-1] = part1 + replaceString + part2
with open(filePath,"w",encoding="utf8") as file:
for line in lines:
file.write(line)
file.close()
#Compare with old line, to confirm the replacement
with open(filePath,"r",encoding="utf8") as file:
if file.readlines()[lineNumber-1] != oldLineContent:
fsifList.insert(0,{f"Found occurence of {searchString} at line number {lineNumber} and Replace of nth occurence is success"})
else:
if aboveLineContent.lower() in lines[lineNumber-2].lower():
if searchString.lower() in lines[lineNumber-1].lower():
arr=re.split(searchString,lines[lineNumber-1],flags=re.IGNORECASE)
part1=searchString.join(arr[:occurenceNumber])
part2=searchString.join(arr[occurenceNumber:])
lines[lineNumber-1] = part1 + replaceString + part2
with open(filePath,"w",encoding="utf8") as file:
for line in lines:
file.write(line)
file.close()
#Compare with old line, to confirm the replacement
with open(filePath,"r",encoding="utf8") as file:
if file.readlines()[lineNumber-1] != oldLineContent:
fsifList.insert(0,{f"Found occurence of {searchString} at line number {lineNumber} and Replace of nth occurence is success"})
else:
return f"File has only {len(lines)} lines. Please check the line number."
file.close()
endTime = time.time()
if len(fsifList)==0:
fsifList.insert(0,{f"{searchString} - not found in line or above line content does not match"})
fsifList.insert(0,{'Execution Time in seconds' : "{:.2f}".format(endTime - startTime)})
return fsifList
except Exception as e:
return e
def fsif_and_replace_nth_below_line_match(self,filePath,lineNumber,searchString,replaceString,belowLineContent,caseSensitive):
"""
This Object finds the occurence of the provided string at a line number inside the file using builtin methods and replaces the occurence
only if the contents of the line below contains the belowLineContent<String>. It then returns a list containing dict items such as execution
time, occurence line number and replace status.
Example usage:
| fsif_and_replace_nth_below_line_match | filePath = <String><Path> | lineNumber = <int> | searchString = <String> | replaceString = <String> | belowLineContent = <String> | caseSensitive = <Boolean> |
"""
try:
fsifList = []
startTime = time.time()
#occurenceNumber is 1 since we are replacing the first occurence of search element that we find in the line
occurenceNumber = 1
with open(filePath,"r",encoding="utf8") as file:
lines = file.readlines()
if lineNumber <= len(lines):
oldLineContent = lines[lineNumber-1]
if caseSensitive:
if belowLineContent in lines[lineNumber]:
if searchString in lines[lineNumber-1]:
arr=lines[lineNumber-1].split(searchString)
part1=searchString.join(arr[:occurenceNumber])
part2=searchString.join(arr[occurenceNumber:])
lines[lineNumber-1] = part1 + replaceString + part2
with open(filePath,"w",encoding="utf8") as file:
for line in lines:
file.write(line)
file.close()
#Compare with old line, to confirm the replacement
with open(filePath,"r",encoding="utf8") as file:
if file.readlines()[lineNumber-1] != oldLineContent:
fsifList.insert(0,{f"Found occurence of {searchString} at line number {lineNumber} and Replace of nth occurence is success"})
else:
if belowLineContent.lower() in lines[lineNumber].lower():
if searchString.lower() in lines[lineNumber-1].lower():
arr=re.split(searchString,lines[lineNumber-1],flags=re.IGNORECASE)
part1=searchString.join(arr[:occurenceNumber])
part2=searchString.join(arr[occurenceNumber:])
lines[lineNumber-1] = part1 + replaceString + part2
with open(filePath,"w",encoding="utf8") as file:
for line in lines:
file.write(line)
file.close()
#Compare with old line, to confirm the replacement
with open(filePath,"r",encoding="utf8") as file:
if file.readlines()[lineNumber-1] != oldLineContent:
fsifList.insert(0,{f"Found occurence of {searchString} at line number {lineNumber} and Replace of nth occurence is success"})
else:
return f"File has only {len(lines)} lines. Please check the line number."
file.close()
endTime = time.time()
if len(fsifList)==0:
fsifList.insert(0,{f"{searchString} - not found in line or below line content does not match"})
fsifList.insert(0,{'Execution Time in seconds' : "{:.2f}".format(endTime - startTime)})
return fsifList
except Exception as e:
return e
def fsif_and_number_of_occurences_extended(self,filePath,searchString,caseSensitive):
try:
fsifList = []
startTime = time.time()
with open(filePath,"r",encoding="utf8") as file:
totalOccurence = 0
lines = file.readlines()
for line in lines:
count = 0
if caseSensitive:
if searchString in line:
count = line.count(searchString)
totalOccurence = totalOccurence + count
fsifDict = {'Line number':lines.index(line),'Line':line,'Count':count}
fsifList.append(fsifDict)
else:
searchStringLower = searchString.lower()
lineLower = line.lower()
if searchStringLower in lineLower:
count = lineLower.count(searchStringLower)
totalOccurence = totalOccurence + count
fsifDict = {'Line number':lines.index(line),'Line':line,'Count':count}
fsifList.append(fsifDict)
file.close()
endTime = time.time()
fsifList.insert(0,{'Execution Time in seconds' : "{:.2f}".format(endTime - startTime)})
fsifList.insert(1,{f'Total Occurence of "{searchString}"':totalOccurence})
return fsifList
except Exception as e:
return e