Python Snippets

File handling

You can use a file handle or you can work with file objects using with.  Using with has the benefits of easier-to-read syntax and cleaner exception handling.  Any files that are open will automatically be closed after your done when you use with.

Checking if a File Exists
from pathlib import Path

my_file = Path("/path/to/file")
if my_file.is_file():
    # file exists
Looping Over File Object
myfile = "output.txt"

# file handle
file = open(myfile, "r")         # a=append, r=read, w=write, rw=read/write
for line in file: 
    print(line)

# file object
with open(myfile) as file:
    # read file line by line and output to list
    data = file.readlines()
    for line in data:
        print(line)
Writing To a File
myfile = "output.txt"

# file handle
file = open(myfile, "w")
file.write("Write these lines to your file") 
file.write("And close it when you're done")
file.close()

# file object
with open(myfile) as file:
    file.write("Write these lines to your file")
    file.write("And close it when you're done")
Writing to a File, Option 2
import sys

print("Send this error to stderr", file = sys.stderr)

f_handle = open('/tmp/output_20200511.txt', 'w')
print("Output to file", file = f_handle)
f_handle.close()

Types

Dustin Ingram – Static Typing in Python


VirtualEnv

When trying to run make htmldocs from kernel source, it recommends doing so from a Python virtualenv.  It’s a perfect time to document setting one up (per their recommendation).

sudo yum install -y ImageMagick graphviz python-virtualenv
virtualenv sphinx_1.4
. sphinx_1.4/bin/activate
pip install -r Documentation/sphinx/requirements.txt

XML Parsing

xml.dom.minidom