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
print(os.path.dirname(os.path.realpath(__file__)))

File Handling

Write String To File

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

Read A 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.

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 = fileHandle.read()
fileHandle.close()

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

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

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.
    """

References

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