2024-06-08_simple-python-tricks-4.html


001| #:name::Simple Python Tricks #4
002| #:link::https://thehardcorecoder.com/2024/06/08/simple-python-tricks-4/
003| #:date::2024-06-08
004| #:code::
005| from os import path
006| 
007| filespec = path.join(pathname, subdir, filename)
008| 
009| #:code::
010| from os import path
011| 
012| BasePath = r'C:\users\me\proj'
013| 
014| def some_function_1 (*args, fname, fpath=BasePath):
015|     filespec = path.join(fpath,fname) if fpath else fname
016|     print(f'Filename: {filespec}')
017|     ...
018| 
019| args = [42, 21, 'caramel']
020| some_function_1(*args, fname='foo.txt')
021| some_function_1(*args, fname='foo.txt', fpath=None)
022| some_function_1(*args, fname='foo.txt', fpath=r'c:\users\me\proj\blog')
023| print()
024| some_function_1(*args, fname=r'temp\foo.txt')
025| some_function_1(*args, fname=r'temp\foo.txt', fpath=None)
026| print()
027| some_function_1(*args, fname=r'C:\users\me\proj\blog\foo.txt', fpath=None)
028| some_function_1(*args, fname=r'C:\users\me\proj\blog\foo.txt')
029| print()
030| 
031| #:code::
032| from os import path
033| 
034| def some_function_2 (*args, fname, fpath=None):
035|     filespec = path.join(fpath,fname) if fpath else fname
036|     print(f'Filename: {filespec}')
037|     ...
038| 
039| args = [42, 21, 'caramel']
040| some_function_2(*args, fname='foo.txt')
041| some_function_2(*args, fname='foo.txt', fpath=None)
042| some_function_2(*args, fname='foo.txt', fpath=r'c:\users\me\proj\blog')
043| print()
044| some_function_2(*args, fname=r'temp\foo.txt')
045| some_function_2(*args, fname=r'temp\foo.txt', fpath=r'c:\users\me')
046| print()
047| some_function_2(*args, fname=r'C:\users\me\proj\blog\foo.txt')
048| some_function_2(*args, fname=r'C:\users\me\proj\blog\foo.txt', fpath=r'D:\backup')
049| print()
050| 
051| #:code::
052| from os import path
053| 
054| BasePath = r'C:\demo\hcc\python'
055| filename = 'the-dream.txt'
056| 
057| fn = path.join(BasePath, filename)
058| fp = open(fn, mode='r', encoding='utf8')
059| lines = fp.readlines()
060| fp.close()
061| 
062| print(f'read: {fn}')
063| print(f'lines: {len(lines)}')
064| print()
065| for line in lines:
066|     print(line, end='')
067| print()
068| 
069| #:code::
070| from os import path
071| 
072| BasePath = r'C:\demo\hcc\python'
073| filename = 'the-dream.txt'
074| 
075| fn = path.join(BasePath, filename)
076| fp = open(fn, mode='r', encoding='utf8')
077| try:
078|     lines = fp.readlines()
079| except Exception as e:
080|     print(e)
081|     raise
082| else:
083|     print(f'read: {fn}')
084|     print(f'lines: {len(lines)}')
085| finally:
086|     fp.close()
087| 
088| print()
089| for line in lines:
090|     print(line, end='')
091| print()
092| 
093| #:code::
094| from os import path
095| 
096| BasePath = r'C:\demo\hcc\python'
097| filename = 'the-dream.txt'
098| 
099| fn = path.join(BasePath, filename)
100| with open(fn, mode='r', encoding='utf8') as fp:
101|     data = fp.read()
102| 
103| print(f'read: {fn}')
104| print(f'chars: {len(data)}')
105| print()
106| print(data)
107| print()
108| 
109| #:code::
110| from os import path
111| from time import localtime
112| from datetime import datetime
113| 
114| class fileobj:
115|     '''File Object class.'''
116| 
117|     def __init__ (self, filename):
118|         '''New File Object instance.'''
119|         self.fullname = filename
120| 
121|         # Parse the full name into parts...
122|         t = path.split(self.fullname)
123|         self.pathname = t[0]
124|         self.filename = t[1]
125|         t = path.splitext(self.filename)
126|         self.name  = t[0]
127|         self.ext = t[1][1:]
128| 
129|         # Default file properties...
130|         self.fsize = 0
131|         self.created = None
132|         self.updated = None
133| 
134|         # If the file exists, get its properties...
135|         self.dflag = False
136|         self.fflag = False
137|         self.xflag = path.exists(self.fullname)
138|         if self.xflag:
139|             # Exists!...
140|             self.dflag = path.isdir(self.fullname)
141|             self.fflag = path.isfile(self.fullname)
142| 
143|             # And it's a file!...
144|             if self.fflag:
145|                 # File Size...
146|                 self.fsize = path.getsize(self.fullname)
147|                 # File Create Date/Time...
148|                 t = localtime(path.getctime(self.fullname))
149|                 self.created = datetime(*t[0:6])
150|                 # File Updated Date/Time...
151|                 t = localtime(path.getmtime(self.fullname))
152|                 self.updated = datetime(*t[0:6])
153| 
154|     def __getattribute__ (self, name):
155|         '''Enable virtual attributes.'''
156|         if name == 'exists': return self.xflag
157|         if name == 'isfile': return self.fflag
158|         if name == 'isdir':  return self.dflag
159|         return super().__getattribute__(name)
160| 
161|     def __bool__ (self):
162|         '''Boolean value: True if file exists.'''
163|         return True if self.xflag else False
164| 
165|     def __eq__ (self, other): return (self.fullname == other.fullname)
166|     def __lt__ (self, other): return (self.fullname < other.fullname)
167|     def __gt__ (self, other): return (other < self)
168|     def __le__ (self, other): return not (self < other)
169|     def __ge__ (self, other): return not (other < self)
170|     def __ne__ (self, other): return not (self == other)
171| 
172|     def __str__ (self): return f'{self.fullname} ({self.fsize} bytes)'
173| 
174| fn = r"C:\demo\hcc\python\the-dream.txt"
175| fo = fileobj(fn)
176| 
177| print(f'{fo=!s}')
178| print(f'{fo.fullname=}')
179| print(f'{fo.pathname=}')
180| print(f'{fo.filename=}')
181| print(f'{fo.name=}')
182| print(f'{fo.ext=}')
183| print(f'{fo.fsize=}')
184| print(f'{fo.created=}')
185| print(f'{fo.updated=}')
186| print(f'{fo.exists=}')
187| print(f'{fo.isfile=}')
188| print(f'{fo.isdir=}')
189| 
190| #:code::
191| from examples import fileobj
192| 
193| class filecontent (fileobj):
194|     '''Abstract File base class.'''
195| 
196|     def __init__ (self, filename):
197|         '''New File Object instance.'''
198|         super().__init__(filename)
199|         self.data = None
200| 
201|     def __len__ (self):
202|         '''File Object's length is the length of its data.'''
203|         return len(self.data)
204| 
205|     def __getitem__ (self, ix):
206|         '''Get a datum by index. (Assumes data is indexable!)'''
207|         return self.data[ix]
208| 
209|     def __setitem__ (self, ix, value):
210|         '''Set a datum by index. (Assumes data is indexable!)'''
211|         self.data[ix] = value
212| 
213|     def __iter__ (self):
214|         '''Set a datum by index. (Assumes data is iterable!)'''
215|         return iter(self.data)
216| 
217| #:end:code::
218|