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__)))
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();
w) intead of the append flag (
a) when opening the zip file.
Send API Request And Get Response JSON String
import requests import json response = requests.get('https://api.somedomain.com') content = json.dumps(response.json())
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()
- Github - Asabeneh / 30-Days-Of-Python
- Stack Overflow - Single vs double quotes in JSON
- Stack Overflow - How can I find script's directory? [duplicate]
- TechRepublic - Writing and appending to zip archives in Python
First published: 20th April 2021