Programster's Blog

Tutorials focusing on Linux, programming, and open-source

Python Cheatsheet

Related Posts

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

File Handling

Write String To File

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

Read A File Into A Variable

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

Loop Over Files In Directory

import os

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

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("", "a")

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('')
content = json.dumps(response.json())

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

Working With JSON

Fix "Bad JSON" Dump

The following snippet will fix situations where a python dictionary was dumped to a file instead of JSON. This would happen if someone were to leave out thee json.dumps step in the snippet above.

import ast
import json

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

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

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


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.


Last updated: 3rd September 2021
First published: 20th April 2021