2024-06-22_simple-python-tricks-5.html


001| #:name::Simple Python Tricks #5
002| #:link::https://thehardcorecoder.com/2024/06/22/simple-python-tricks-5/
003| #:date::2024-06-22
004| #:code::
005| from examples import filecontent
006| 
007| class datafile (filecontent):
008|     '''Generic Data File class.'''
009| 
010|     def __init__ (self, filename):
011|         ''' New Data File instance.'''
012|         super().__init__(filename)
013|         self.data = None
014| 
015|     def load (self):
016|         '''Load data file. (Data will be bytes.)'''
017|         fp = open(self.fullname, mode='rb')
018|         try:
019|             self.data = fp.read()
020|         except Exception as e:
021|             print(e)
022|             raise
023|         else:
024|             print(f'read: {self.fullname}')
025|         finally:
026|             fp.close()
027| 
028|     def save (self, data=None):
029|         '''Save data file. (Data must be bytes.)'''
030|         fp = open(self.fullname, mode='wb')
031|         try:
032|             fp.write(self.data)
033|         except Exception as e:
034|             print(e)
035|             raise
036|         else:
037|             print(f'wrote: {self.fullname}')
038|         finally:
039|             fp.close()
040| 
041|     def __contains__ (self, item): return (item in self.data)
042| 
043| from os import path
044| 
045| BasePath = r'C:\demo\hcc\python'
046| filename = r'colors.png'
047| 
048| fn = path.join(BasePath, filename)
049| fo = datafile(fn)
050| fo.load()
051| 
052| print()
053| print(f'{fo.filename=}')
054| print(f'{len(fo)=}')
055| print(f'{fo[0:10]=}')
056| print(f'{fo[9]=}')
057| for b in fo:
058|     print(f'{b=:02x}')
059|     if b == ord('\n'):
060|         break
061| print()
062| 
063| #:code::
064| from examples import filecontent
065| 
066| class textfile (filecontent):
067|     '''Generic Text File class.'''
068| 
069|     def __init__ (self, filename):
070|         ''' New Text File instance.'''
071|         super().__init__(filename)
072|         self.data = str()
073| 
074|     def load (self, encoding='utf-8'):
075|         '''Load text file. (Data will be a single string.)'''
076|         fp = open(self.fullname, mode='r', encoding=encoding)
077|         try:
078|             # Read string from file...
079|             self.data = fp.read()
080| 
081|             # Check for a Unicode BOM...
082|             if self.data[0] == '\ufeff':
083|                 # Remove it if found...
084|                 self.data = self.data[1:]
085|         except Exception as e:
086|             print(e)
087|             raise
088|         else:
089|             print(f'read: {self.fullname}')
090|         finally:
091|             fp.close()
092| 
093|     def save (self, encoding='utf-8', use_bom=False):
094|         '''Save text file. (Data must be a single string.)'''
095|         fp = open(self.fullname, mode='w', encoding=encoding)
096|         try:
097|             # Optional Unicode BOM marker...
098|             if use_bom:
099|                 fp.write('\ufeff')
100| 
101|             # Write string to file...
102|             fp.write(self.data)
103|         except Exception as e:
104|             print(e)
105|             raise
106|         else:
107|             print(f'wrote: {self.fullname}')
108|         finally:
109|             fp.close()
110| 
111|     def __contains__ (self, item): return (item in self.data)
112| 
113| from os import path
114| 
115| BasePath = r'C:\demo\hcc\python'
116| filename = r'the-dream.txt'
117| 
118| fn = path.join(BasePath, filename)
119| fo = textfile(fn)
120| fo.load()
121| 
122| print()
123| print(f'{fo.filename=}')
124| print(f'{len(fo)=}')
125| print(f'{fo[0:60]=}')
126| print(f'{fo[100]=}')
127| print(f'{"house" in fo=}')
128| print(f'{"foobar" in fo=}')
129| nbr_of_spaces = 0
130| for ch in fo:
131|     if ch == ' ':
132|         nbr_of_spaces += 1
133| print(f'{nbr_of_spaces=}')
134| print()
135| 
136| #:code::
137| from examples import filecontent
138| 
139| class linefile (filecontent):
140|     '''Line-oriented Text File class.'''
141| 
142|     def __init__ (self, filename):
143|         ''' New Text File instance.'''
144|         super().__init__(filename)
145|         self.data = []
146| 
147|     def __call__ (self):
148|         '''Calling object returns lines as single string.'''
149|         return '\n'.join(self.data)
150| 
151|     def add (self, txt=''):
152|         '''Add's a new line to the end of the data.'''
153|         self.data.append(txt)
154| 
155|     def load (self, encoding='utf-8'):
156|         '''Load text file. (Data will be a list of strings.)'''
157|         fp = open(self.fullname, mode='r', encoding=encoding)
158|         try:
159|             # Read lines from file...
160|             self.data = [s.rstrip() for s in fp]
161| 
162|             # Check for a Unicode BOM...
163|             if 0 < len(self.data):
164|                 if 0 < len(self.data[0]):
165|                     if self.data[0][0] == '\ufeff':
166|                         self.data[0] = self.data[0][1:]
167|         except:
168|             raise
169|         else:
170|             print(f'read: {self.fullname}')
171|         finally:
172|             fp.close()
173| 
174|     def save (self, encoding='utf-8', use_bom=False):
175|         '''Save text file. (Data must be a list of strings.)'''
176|         fp = open(self.fullname, mode='w', encoding=encoding)
177|         try:
178|             # Optional Unicode BOM marker...
179|             if use_bom:
180|                 fp.write('\ufeff')
181| 
182|             # Write lines to file...
183|             for s in self.data:
184|                 fp.write(s)
185|                 fp.write('\n')
186|         except:
187|             raise
188|         else:
189|             print(f'wrote: {self.fullname}')
190|         finally:
191|             fp.close()
192| 
193| fn = r'C:\demo\hcc\python\the-dream.txt'
194| fo = linefile(fn)
195| fo.load()
196| 
197| print()
198| print(f'{fo.filename=}')
199| print(f'{len(fo)=}')
200| print(f'{fo[3:5]=}')
201| print()
202| for line in fo:
203|     print(line)
204|     if line.startswith('I dreamed'):
205|         break
206| print()
207| 
208| #:code::
209| from os import path
210| from examples import linefile
211| 
212| BasePath = r'C:\demo\hcc\python'
213| filename = r'2b-or-not2b.txt'
214| 
215| fn = path.join(BasePath, filename)
216| fo = linefile(fn)
217| fo.add("To be, or not to be: that is the question:")
218| fo.add("Whether 'tis nobler in the mind to suffer")
219| fo.add("The slings and arrows of outrageous fortune,")
220| fo.add("Or to take arms against a sea of troubles,")
221| fo.add("And by opposing end them? To die: to sleep;")
222| fo.add("No more; and by a sleep to say we end")
223| fo.add("The heart-ache and the thousand natural shocks")
224| fo.add("That flesh is heir to, 'tis a consummation")
225| fo.add("Devoutly to be wish'd. To die, to sleep;")
226| fo.add("To sleep: perchance to dream: ay, there's the rub;")
227| fo.save(use_bom=True)
228| 
229| #:code::
230| from json import load as jsonload, dump as jsonsave
231| from examples import filecontent
232| 
233| class jsonfile (filecontent):
234|     '''JSON (Text) File class.'''
235| 
236|     def __init__ (self, filename):
237|         ''' New JSON File instance.'''
238|         super().__init__(filename)
239|         self.data = {}
240| 
241|     def load (self):
242|         '''Load JSON file. (Data will be a dictionary.)'''
243|         fp = open(self.fullname, mode='rb')
244|         try:
245|             # Load a JSON file...
246|             self.data = jsonload(fp)
247|         except:
248|             raise
249|         else:
250|             print(f'read: {self.fullname}')
251|         finally:
252|             fp.close()
253| 
254|     def save (self, indent=3):
255|         '''Save JSON file. (Data must be a dictionary.)'''
256|         fp = open(self.fullname, mode='w')
257|         try:
258|             # Write a JSON file...
259|             jsonsave(self.data, fp, indent=indent)
260|         except:
261|             raise
262|         else:
263|             print(f'wrote: {self.fullname}')
264|         finally:
265|             fp.close()
266| 
267| fn = r'C:\demo\hcc\python\example.json'
268| fo = jsonfile(fn)
269| fo.load()
270| 
271| print(fo)
272| print()
273| print(f'{len(fo)=} (# of top-level dicts)')
274| print(f'Top-level dicts: {list(fo.data.keys())}')
275| print()
276| print(f'{fo.data["version"]=}')
277| print(f'{fo.data["head"]["title"]=}')
278| print()
279| 
280| #:code::
281| from examples import jsonfile
282| 
283| fn = r'C:\demo\hcc\python\output.json'
284| fo = jsonfile(fn)
285| 
286| fo.data = {'artist':{}, 'album':{}}
287| fo['artist']['firstname'] = "Joanne"
288| fo['artist']['midname'] = "Shaw"
289| fo['artist']['lastname'] = "Taylor"
290| fo['album']['name'] = "Diamonds in the Dirt"
291| fo['album']['date'] = 2010
292| fo['album']['length'] = [0, 43, 21]
293| fo['album']['songs'] = []
294| 
295| fo.save()
296| 
297| #:code::
298| from examples import linefile
299| 
300| class srcfile (linefile):
301|     '''Source Code File class. Auto-skips blank lines and comments.'''
302|     def __init__ (self, filename, rems=None):
303|         super().__init__(filename)
304|         self.rems = rems if rems else [';', '#', '//', '--']
305|         self.src = []
306| 
307|     def load (self):
308|         '''Load Source Code file. (Code lines will be in a list.)'''
309|         # Delegate loading lines of text to parent...
310|         super().load()
311| 
312|         # Scan file lines for blank lines and comments...
313|         for line in self.data:
314|             # Ignore leading and trailing spaces...
315|             test = line.strip()
316| 
317|             # Skip blank lines...
318|             if len(test) == 0:
319|                 continue
320| 
321|             # Skip lines beginning with rem char...
322|             rem_flag = 0
323|             for rem in self.rems:
324|                 if test.startswith(rem):
325|                     rem_flag = 1
326|                     break
327|             if rem_flag:
328|                 continue
329| 
330|             # Add the line to the src code...
331|             self.src.append(line)
332| 
333|     def save (self):
334|         raise NotImplementedError()
335| 
336| fn = r'C:\demo\hcc\python\vim.txt'
337| fo = srcfile(fn, rems=['"'])
338| fo.load()
339| 
340| for ix,line in enumerate(fo.src):
341|     print(f'{ix+1:02d}: {line}')
342| print()
343| 
344| #:end:code::
345|