javiloz1604
javiloz1604

Reputation: 21

How to import variables from another file AFTER the program has started in python?

I want to create a program that makes the user select a file, and that file will contain a series of variables (like dictionaries and lists) that the program will use. Now, I know there's the import file function but I can't use it because that's supposed to be at the beginning of the program (the user has to select which program wants to load first). The only step that's left in my program is the one that loads the variables, I know how to do the rest. Could anyone help me? Thank you in advance!

Upvotes: 0

Views: 177

Answers (1)

felix
felix

Reputation: 169

You could just use

with open(file, "r") as f:
    data = f.read().splitlines()

to read the data, assuming every variable is on its own line. This will read in all variables in the file file as a list called data containing each file line as one entry.

Note that this will read all variables in as strings, so you may have to cast to different types before actually using the values.

Upvotes: 1

Related Questions