Python

File actions

ModeDescription
rOpen a file for reading mode. (Default if mode is not specified)
wOpen a file for writing. Will create a new file if does not exist or truncates/overwrites content if the file exists.
xOpen a file for exclusive creation.
aOpen a file for appending the text. Will create a new file if does not exist.
tOpen a file in text mode. (Default)
bOpen a file in binary mode.
+Open a file for updating (reading and writing)

Write text file

Open file and append to content:

file = open("data.txt", "a")
file.write("Wohoo! Added to existing content!")
file.close()

Open file and overwrite the content:

file = open("data.txt", "w")
file.write("Wohoo! Original content is gone!")
file.close()

Read text file

Open file and read content:

file = open("data.txt", "r")
content = file.read()
print(content)
file.close()

Open file and read line by line:

file = open("data.txt", "r")
while True:
	content=file.readline()
	if not content:
		break
	print(content)
file.close()

Open file and read file as list of strings:

file = open("data.txt", "r")
content = file.readlines()
print(content)
file.close()

Json actions

Read json file

import json
 
with open("data.json") as file:
    data = json.load(file)
    print(data)

Modify json data

data[0]['age'] = 44 # change specifig entry
data.append({"name": "Joe"}) # append new entry
data.insert(0, {"name": "Jimmy"}) # add new entry at specific index

Write json data

new_data = json.dumps(data, indent=4)

with open("new_data.json", "w") as file:
    file.write(new_data)

MongoDB

Connect database

from pymongo import MongoClient

CONNECTION_STRING = "mongodb://192.168.178.6/pymongo_shopping_list"
client = MongoClient(CONNECTION_STRING)

dbname = client["pymongo"]

Connect to collection

collection = dbname["data"]

Insert data

collection.insert_one({"name": "Joe"})

Insert data from json

import json

...

with open("data.json") as file:
    data = json.load(file)
    collection_name.insert_many(data)

Find data

cursor = collection.find()

for document in cursor:
    print(document)

Update data

for document in cursor:
    print(document["name"])
    if document["name"] == "Bobby":
        document["name"] = "Bob"
        print(document)
        collection.update_one({"_id": document["_id"]}, { "$set": document })

Flask

Simple flask app

Reference: https://flask.palletsprojects.com/en/2.3.x/quickstart/

python -m flask –app .\flask.py run

from flask import Flask

app = Flask(__name__)

@app.route("/")
def hello_world():
    return '{"status": "OK"}'

API

GET

Simple API requests using “requests” module

import requests

response = requests.get("http://127.0.0.1:5000/")
print(response.json())