Programming

Input and output: input, files, JSON

Read user input, write to a file and read from it.

All lessons · Python lessons: learn from scratch

Reading from the user

input() returns what the user typed, always as a str. If you need a number, convert it with int() or float(). A wrong entry can raise an error, so guard it with try.

raw = input("How many tickets? ")
try:
    n = int(raw)
    print("Total:", n * 8, "AZN")
except ValueError:
    print("Please type a whole number")

Working with files

Open a file with with open(...): it closes automatically when the block ends. Modes: "r" read, "w" write (erases the old content), "a" append. Specify encoding="utf-8" for non-English letters.

with open("notes.txt", "w", encoding="utf-8") as f:
    f.write("first\n")
    f.write("second\n")

with open("notes.txt", encoding="utf-8") as f:
    for line in f:
        print(line.strip())

Saving data as JSON

The json module is a convenient way to write lists and dictionaries to a file; the result is human-readable and compatible with other languages.

import json

data = {"user": "Sevda", "scores": [90, 85]}
with open("data.json", "w", encoding="utf-8") as f:
    json.dump(data, f, ensure_ascii=False, indent=2)

with open("data.json", encoding="utf-8") as f:
    back = json.load(f)
print(back["scores"])

Author: Nibras Code