2026-04-06_this-is-python.html


001| #:name::This is Python! (part 11)
002| #:link::https://thehardcorecoder.com/2026/04/06/this-is-python-part-11/
003| #:date::2026-04-06
004| #:code::
005| ### Reading a text file...
006| 
007| filename = r"C:\Demo\HCC\Python\Python Zen.txt"
008| 
009| # Open the file...
010| file_in = open(filename)
011| 
012| # Read the entire file contents...
013| file_content = file_in.read()
014| 
015| # Close the file...
016| file_in.close()
017| 
018| # Print the file contents...
019| print(file_content)
020| 
021| #:code::
022| # Using a regular string...
023| filename = "C:\Demo\HCC\Python\Python Zen.txt"
024| print(filename)
025| print()
026| 
027| # Using a regular string with double backslashes...
028| filename = "C:\\Demo\\HCC\\Python\\Python Zen.txt"
029| print(filename)
030| print()
031| 
032| # Using a raw string...
033| filename = r"C:\Demo\HCC\Python\Python Zen.txt"
034| print(filename)
035| print()
036| 
037| # Using a raw+format string...
038| which_file = "Python Zen"
039| 
040| filename = rf"C:\Demo\HCC\Python\{which_file}.txt"
041| print(filename)
042| print()
043| 
044| #:code::
045| ### Reading a text file...
046| 
047| filename = r"C:\Demo\HCC\Python\Python Zen.txt"
048| 
049| # Open the file...
050| file_in = open(filename)
051| 
052| # Read the entire file contents...
053| file_content = file_in.readlines()
054| 
055| # Close the file...
056| file_in.close()
057| 
058| print(f'file_content is a {type(file_content)}.')
059| print(f'file_content has {len(file_content)} lines.')
060| print()
061| 
062| #:code::
063| ### Reading a text file...
064| 
065| filename = r"C:\Demo\HCC\Python\Python Zen.txt"
066| 
067| # Open the file...
068| file_in = open(filename)
069| 
070| # Read the entire file contents...
071| file_content = list(file_in)
072| 
073| # Close the file...
074| file_in.close()
075| 
076| print(f'file_content is a {type(file_content)}.')
077| print(f'file_content has {len(file_content)} lines.')
078| print()
079| 
080| #:code::
081| ### Reading a text file...
082| 
083| filename = r"C:\Demo\HCC\Python\Python Zen.txt"
084| 
085| # Open the file...
086| file_in = open(filename)
087| 
088| # Print the file contents...
089| for line in file_in:
090|     print(line)
091| print()
092| 
093| # Close the file...
094| file_in.close()
095| 
096| #:code::
097| ### Reading a text file...
098| 
099| filename = r"C:\Demo\HCC\Python\Python Zen.txt"
100| 
101| # Open the file...
102| file_in = open(filename)
103| 
104| # Print the file contents...
105| for line in file_in:
106|     print(line, end='')
107| print()
108| 
109| # Close the file...
110| file_in.close()
111| 
112| #:code::
113| ### Reading a text file...
114| 
115| filename = r"C:\Demo\HCC\Python\Python Zen.txt"
116| 
117| # Open the file...
118| file_in = open(filename)
119| 
120| # Print the file contents...
121| for line in file_in:
122|     line = line.rstrip()
123|     print(line)
124| print()
125| 
126| # Close the file...
127| file_in.close()
128| 
129| #:code::
130| ### Writing a text file...
131| 
132| filename = r"C:\Demo\HCC\Python\output.txt"
133| 
134| # Open the file...
135| file_out = open(filename, mode="w")
136| print(f'opened: {filename}')
137| print()
138| 
139| try:
140|     # Write the output data...
141|     for datum in big_list_of_data:
142| 
143|         # Process the data...
144|         temp = first_process(datum)
145|         line = second_process(temp)
146| 
147|         # Write data to file...
148|         file_out.write(line)
149| 
150| except Exception as e:
151|     print(f'ErrType: {type(e).__name__}')
152|     print(f'ErrText: {e}')
153|     print()
154| 
155| else:
156|     print('Wrote all data successfully!')
157| 
158| finally:
159|     # Close the file...
160|     file_out.close()
161|     print(f'closed: {filename}')
162|     print()
163| 
164| #:code::
165| ### Reading a text file using with...
166| 
167| filename = r"C:\Demo\HCC\Python\Python Zen.txt"
168| 
169| # Open the file with context manager...
170| with open(filename) as file_in:
171| 
172|     # Print the file contents...
173|     for line in file_in:
174|         print(line, end='')
175|     print()
176| 
177| #:code::
178| ### Writing a text file using with...
179| 
180| filename = r"C:\Demo\HCC\Python\output.txt"
181| 
182| # Open the file...
183| with open(filename, mode="w") as file_out:
184| 
185|     for line in big_list_of_data:
186| 
187|         # Process the data...
188|         line = first_process(line)
189|         line = second_process(line)
190| 
191|         # Write data to file...
192|         file_out.write(line)
193| 
194| #:code::
195| ### Convert Python Zen to Rotated Zen...
196| 
197| basepath = r"C:\Demo\HCC\Python"
198| filename_in = rf"{basepath}\Python Zen.txt"
199| filename_out = rf"{basepath}\Rotated Zen.txt"
200| 
201| 
202| # Read input file with context manager...
203| with open(filename_in) as file_in:
204| 
205|     # Get the file contents...
206|     file_text = file_in.read()
207| 
208| print('read: {filename_in} ({len(file_text)} chars)')
209| 
210| 
211| # Write output file with context manager...
212| with open(filename_out, mode="w") as file_out:
213| 
214|     # Write ROT13 version to output...
215|     for char in file_text:
216| 
217|         # Get the character index...
218|         cx = ord(char)
219| 
220|         # If it's an uppercase char...
221|         if ord('A') <= cx <= ord('Z'):
222|             # Separate A-M from N-Z...
223|             if cx < ord('N'):
224|                 file_out.write(chr(cx+13))
225|             else:
226|                 file_out.write(chr(cx-13))
227| 
228|             # Next char...
229|             continue
230| 
231|         # If it's a lowercase char...
232|         if ord('a') <= cx <= ord('z'):
233|             # Separate a-m from n-z...
234|             if cx < ord('n'):
235|                 file_out.write(chr(cx+13))
236|             else:
237|                 file_out.write(chr(cx-13))
238| 
239|             # Next char...
240|             continue
241| 
242|         # Not an alpha-char, so just write it...
243|         file_out.write(char)
244| 
245| print('wrote: {filename_out}')
246| 
247| #:code::
248| ### The os.path module...
249| from os import path
250| 
251| BasePath = r"C:\Demo\HCC\Python"
252| 
253| filename_in = path.join(BasePath, "Python Zen.txt")
254| filename_out = path.join(BasePath, "Rotated Zen.txt")
255| 
256| print(f'input: {filename_in}')
257| print(f'output: {filename_out}')
258| print()
259| 
260| #:NOTE:: mention that forward slash also works!
261| #:code::
262| ### The os.path module...
263| from os import path
264| 
265| BasePath = r"C:\Demo"
266| DemoPath = path.join(BasePath, "HCC", "Python")
267| FileName = path.join(DemoPath, "Python Zen.txt")
268| 
269| print(f'BasePath: {BasePath}')
270| print(f'DemoPath: {DemoPath}')
271| print()
272| print(f'FileName: {FileName}')
273| print(f'basename: {path.basename(FileName)}')
274| print(f'dirname: {path.dirname(FileName)}')
275| print()
276| 
277| print(f'Exists: {path.exists(FileName)}')
278| print(f'IsFile: {path.isfile(FileName)}')
279| print(f'IsDir: {path.isdir(FileName)}')
280| print()
281| 
282| print(f'FileSize: {path.getsize(FileName)} bytes')
283| print(f'DateCreated: {path.getctime(FileName)}')
284| print(f'DateUpdated: {path.getmtime(FileName)}')
285| print(f'LastAccess: {path.getatime(FileName)}')
286| print()
287| 
288| print('Split:')
289| for part in path.split(FileName):
290|     print(part)
291| print()
292| 
293| print('SplitDrive:')
294| for part in path.splitdrive(FileName):
295|     print(part)
296| print()
297| 
298| print('SplitRoot:')
299| for part in path.splitroot(FileName):
300|     print(part)
301| print()
302| 
303| print('SplitExt:')
304| for part in path.splitext(FileName):
305|     print(part)
306| print()
307| 
308| #:code::
309| ### Generate related filenames...
310| from os import path
311| 
312| LogsPath = r"C:\Demo\logs\hcc"
313| 
314| def get_related_filenames (filename):
315|     """Generate output and logfile names."""
316| 
317|     # Divide filename into fpath and fname...
318|     fpath, fname = path.split(filename)
319| 
320|     # Divide fname into name and ext...
321|     name, ext = path.splitext(fname)
322| 
323|     print(f'{fpath = }')
324|     print(f'{fname = }')
325|     print(f'{name = }')
326|     print(f'{ext = }')
327|     print()
328| 
329|     # Create output name...
330|     outname = path.join(fpath, f'{name}.out')
331| 
332|     # Create logfile name...
333|     logname = path.join(LogsPath, f'{name}.log')
334| 
335|     # Return all three filenames...
336|     return (filename, outname, logname)
337| 
338| 
339| zen_file = r"C:\Demo\HCC\Python\data.json"
340| 
341| names = get_related_filenames(zen_file)
342| 
343| print(f'Filename: {names[0]}')
344| print(f'Out-Name: {names[1]}')
345| print(f'Log-Name: {names[2]}')
346| print()
347| 
348| #:code::
349| from os import path
350| 
351| # Folder where our files are...
352| BasePath = r'C:\Demo\HCC\Python'
353| 
354| # Binary file we want to read...
355| DataFile = 'bitmap-pi.png'
356| 
357| # Create the full path/filename...
358| filename = path.join(BasePath, DataFile)
359| 
360| # Let's see how big it is...
361| filesize = path.getsize(filename)
362| print(f'{DataFile} has {filesize} bytes.')
363| print()
364| 
365| # Open and read binary file...
366| with open(filename, mode='rb') as file_in:
367|     data = file_in.read()
368| 
369| # Display some results...
370| print(f'read {len(data)} bytes.')
371| print(f'data type is {type(data)}.')
372| print(f'datum type is {type(data[0])}.')
373| print()
374| 
375| print('First 10 bytes:')
376| for ix,datum in enumerate(data[:10]):
377|     char = chr(datum)
378|     char = char if char.isprintable() else '-'
379|     print(f'{ix}: {datum:02x} ({char})')
380| print()
381| 
382| #:code::
383| from os import listdir
384| 
385| # Folder where our files are...
386| BasePath = r'C:\Demo\HCC\Python'
387| 
388| # Get a list of files there...
389| filelist = listdir(BasePath)
390| 
391| # List the files...
392| for ix,name in enumerate(filelist, start=1):
393|     print(f'{ix:2d}: {name}')
394| print()
395| 
396| #:code::
397| from os import listdir, path
398| 
399| # Folder where our files are...
400| BasePath = r'C:\Demo\HCC\Python'
401| 
402| # Get a list of files there...
403| filelist = listdir(BasePath)
404| 
405| # List the files...
406| for ix,name in enumerate(filelist, start=1):
407|     filename = path.join(BasePath, name)
408|     print(f'{ix:2d}: {filename}')
409| print()
410| 
411| #:code::
412| from os import listdir, path
413| from time import ctime
414| 
415| # Folder where our files are...
416| BasePath = r'C:\Demo\HCC\Python'
417| 
418| # Get a list of files there...
419| filelist = listdir(BasePath)
420| 
421| # List the files...
422| print('Files in {BasePath}:')
423| for ix,name in enumerate(filelist, start=1):
424|     filename = path.join(BasePath, name)
425| 
426|     filesize = f'{path.getsize(filename):,}'
427| 
428|     filedate = ctime(path.getmtime(filename))
429| 
430|     print(f'{ix:2d}: {name:19s} | {filesize:>6} | {filedate}')
431| print()
432| 
433| #:code::
434| from os import listdir, path
435| from time import ctime
436| 
437| # Folder where our files are...
438| BasePath = r'C:\Demo\HCC\Python'
439| 
440| # Get a list of files (and folders) there...
441| names = listdir(BasePath)
442| 
443| # Generate a list of fullnames...
444| filenames = [path.join(BasePath, n) for n in names]
445| 
446| # Get the directory names...
447| dirs = list(filter(path.isdir, filenames))
448| 
449| # Get the filenames...
450| files = list(filter(path.isfile, filenames))
451| 
452| # List directories...
453| print(f'Subfolders found in {BasePath}:')
454| for name in dirs:
455|     print(name)
456| print()
457| 
458| # List files...
459| print(f'Files found in {BasePath}:')
460| for name in files:
461|     print(name)
462| print()
463| 
464| #:code::
465| ...
466| 
467| filenames = []
468| for n in names:
469|     # Create the full path/name...
470|     fullname = path.join(BasePath, n)
471| 
472|     # Append it to the end of the list...
473|     filenames.append(fullname)
474| 
475| ...
476| 
477| #:code::
478| ...
479| 
480| # List directories...
481| print(f'Subfolders found in {BasePath}:')
482| for name in filter(path.isdir, filenames):
483|     print(name)
484| print()
485| 
486| # List files...
487| print(f'Files found in {BasePath}:')
488| for name in filter(path.isfile, filenames):
489|     print(name)
490| print()
491| 
492| #:end:code::
493|