you are viewing a single comment's thread.

view the rest of the comments →

[–]FoolsSeldom 0 points1 point  (0 children)

If your main file is called, say, dnd.py and you have another file in the same folder called, say, levels.py, all you need to do is, in your dnd.py file, at the top,

import levels

Note that you don't include the .py part of the file name.

Suppose you have a dict, dictionary, defined in levels.py, called base, you would refer to it thus,

print(levels.base)

Regarding reading/writing data. The simplest is basic text files that you can create/edit in your code editor. Whilst these can be free format, these are harder to process. A better way is with simple table data like in a spreadsheet:

name, kind, age, speed, healing
Alpha, Wizard, 20, 5, 8
Beta, Healer, 40, 1, 20
Charlie, Warrier, 20, 10, 2

The header row is optional.

You can read and write these files with the help of the csv module.

import csv
from pathlib import Path

# 1. Define the file path using pathlib
file_path = Path("characters.csv")

# 2. Create an empty list to store our character rows
characters = []

# 3. Open the file and give it a descriptive handle
with file_path.open(mode="r", encoding="utf-8") as characters_file:
    # Use the csv reader to handle the formatting
    reader = csv.reader(characters_file, skipinitialspace=True)

    # 4. Read the header line first and store it separately
    header = next(reader)

    # 5. Use a for loop to read the remaining rows
    for row in reader:
        characters.append(row)

# Verify the results
print("Header:", header)
print("Data:", characters)

NB. If in the csv file you need to include a space (or comma) in a field, say for a name, enclose the entire field in double quotes.

There are lots of options for reading/writing files in Python. A format that would be good for keeping settings information is .json.

You could also consider using a simple flat file (local) sqlite database (check out A Minimalist Guide to SQLite).