Python Notes

Contents

I/O, JSON, time, GUI, Data Structures, Strings, Dirs & Files, Admin, os, sys, Control Flow, Introspection Main Templates, Class Templates, Modules, Parsing

I/O [2 Contents]

Read File To List 1Liner


f = open(r'mytest.txt', 'r', encoding="utf-8"); l = f.read().splitlines(); f.close()

Read File To String 1Liner


f = open(r'mytest.txt', 'r', encoding="utf-8"); s = f.read(); f.close()

JSON [2 Contents]

JSON to PythonObj

import json
f = open(r'mytest.json', 'r', encoding="utf-8"); jsonstr = f.read(); f.close()
my_python_obj = json.loads(jsonstr) 
print(my_python_obj)

PythonObj To JSON


import json
my_python_obj = {"first_name": "Guido", "last_name":"Rossum"}
my_python_obj_json_str = json.dumps(my_python_obj) 
f = open('my_python_obj.json', 'w', encoding="utf-8"); f.write(my_python_obj_json_str); f.close()

time [2 Contents]

Time Stamps Duration


import datetime

dt_begin = datetime.datetime.now()
# DO YOUR STUFF IN HERE
dt_end = datetime.datetime.now()
  
print( "End Timestamp: %s"%(str(dt_end).replace(':', '.').replace(' ', '_'))     )
print( "Begin Timestamp: %s"%(str(dt_begin).replace(':', '.').replace(' ', '_')) )
print( " (End - Begin): %s"%(dt_end - dt_begin))  

GUI [2 Contents]

tk simple dialog


# -*- coding: utf-8 -*-
r""" tkAskString.py uses TK to ask the user for a string & prints it out
Usage:   ./tkAskString.py 
Sample:  ./tkAskString.py 
see: 
  1. ["Example 2" - Python tkinter.simpledialog.askstring() Examples](https://www.programcreek.com/python/example/100669/tkinter.simpledialog.askstring)
  2. [How do I get rid of Python Tkinter root window?](https://stackoverflow.com/questions/1406145/how-do-i-get-rid-of-python-tkinter-root-window)
  3. [Tkinter Dialogs (Python3.10)](https://docs.python.org/3/library/dialog.html)
  4. google: tkinter simpledialog set width   |   tkinter simpledialog keyword arguments  
  5. ["add extra tabs at the end of your prompt"](https://stackoverflow.com/a/69396488/601770)
"""
import tkinter as tk
from tkinter import simpledialog
# root = tk.Tk()
  
def main():
    root = tk.Tk()
    root.withdraw()
    uname = simpledialog.askstring("My Title", "Enter username:\t\t\t") # Tabs make it wide as i want
      
    print(uname)
    return uname
  
if __name__ == "__main__":
    main()