Programster's Blog

Tutorials focusing on Linux, programming, and open-source

Python Cheatsheet

Below is my cheat-sheet for Python. Please note, this assumes Python 3 as most Linux distributions have finally made the switch.

Table Of Contents

Related Posts

File Handling  

Write String To File  

content = "hello world"
text_file = open("output.json", "w")
text_file.write(content)
text_file.close()

Read File Into A Variable  

fileHandler = open("/path/to/file.txt", "r")
content = fileHandler.read() 

Loop Over Files In Directory  

import os

for filename in os.listdir("/path/to/directory"):
    print(filename)

Add File To A Zip  

If the zip file doesn't already exist, this will create one. If it does already exist, this will add the file to it.

import zipfile
zipClient = zipfile.ZipFile("myZip.zip", "a")
zipClient.write("myfile.txt")
zipClient.close();

If you want to ensure that you are not appending to a zip file, and wish to replace it if one already exists, simply use the write flag (w) intead of the append flag (a) when opening the zip file.

API Requests  

Send API Request And Get Response JSON String

import requests
import json

response = requests.get('https://api.somedomain.com')
content = json.dumps(response.json())

Without the json.dumps you will end up with a Python dictionary instead of a JSON string.

JSON  

Importing / Exporting Examples  

Refer here

Fix "Bad JSON" Dump  

The following snippet will fix situations where a python dictionary was dumped to a file instead of JSON.

import ast
import json

fileHandle = open("output.json", "r")
pythonDictString = fileHandle.read()
fileHandle.close()

pythonDataObj = ast.literal_eval(pythonDictString)
jsonString = json.dumps(pythonDataObj);

fileHandle = open("output.json", "w");
fileHandle.write(jsonString)
fileHandle.close()

The snippet below would result in an example file that would look like JSON but wasn't (and would need fixing):

import requests
import json

response = requests.get('https://api.somedomain.com')
content = response.json() # content is dictionary, not JSON string!

fileHandle = open("output.json", "w");
fileHandle.write(content)
fileHandle.close()

Conventions  

Private Variables and Methods  

Python does not have private member variables and methods. Instead, programmers rely on a naming convention whereby such variables/methods are prefixed with _. Developers know not using another class's methods/variables that start with this in the name.

class MyClass:
    _my_private_member_variable: str

    def myPublicAccessor(self):
        return self._my_private_member_variable

Function Documentation  

To document a function, there is the Sphinx markup which is supported by Pycharm. Below is an example:

def sayHello(name=None)
    """
    Generate a hello message

    :param str name: optionally specify the name of the person to say hello to.
    :return str: The generated message.
    """

Misc  

Get Script's Directory  

This will return the full path to the directory that contains the script. This may or may not be where you called the script from.

import os
print(os.path.dirname(os.path.realpath(__file__)))

Get Command Line Arguments  

import sys

scriptName = sys.argv[0]
firstArgument = sys.argv[1]
listOfJustTheArguments = sys.argv[1:]

Output To Stderr  

print("Message to put out in stderr", file=sys.stderr)

Exit / Quit  

There are many ways to quit out in Python, but the rule-of-thumb would e to just use the following:

sys.exit("My exit/error message")
  • quit() and exit() are synonyms and raise the SystemExit exception behind the scenes and only available if the site module is imported.
  • sys.exit() is considered good to be used in production code because the sys module is always available.
  • os._exit() function is special because it exits immediately without calling any cleanup functions. It doesnt flush buffers for example.
  • If entering a message in any of them (except os._exit which needs an exit integer), they will always exit in such a way that if using set -e in a BASH script to stop on error, the BASH script would stop (e.g. you do not need to worry about using an exit code of 1)
  • Any messages in such calls to to the stderr stream (except os._exit which needs an exit integer)
  • Using any of them without any parameters, will result in the script exiting as if it ran successfully, so be sure to put something in if something went wrong! This way if called from BASH with set -e the BASH script can know to stop.

References  

Last updated: 5th March 2022
First published: 20th April 2021

This blog is created by Stuart Page

I'm a freelance web developer and technology consultant based in Surrey, UK, with over 10 years experience in web development, DevOps, Linux Administration, and IT solutions.

Need support with your infrastructure or web services?

Get in touch