Search code examples
pythonfile-ioimportmodulepython-module

Print items from a list in an external .py file


I have a list in a external file and I'm able to access the file but I have a list in that file with the name of factswith some items on it but how can I read the items from that list? It goes something like

x = open("Trivia"+"/fact.py", "r")
f = x.read()
fact = f.? 

What do I have to do there? If I run the code like that it just prints the whole list with the variable name and everything.


Solution

  • open is for files containing data; files containing Python code are typically accessed with import. See The Python Tutorial's section 6. Modules for the typical use cases.

    Assuming you'll always be running your script from the same directory:

    import Trivia.fact
    
    do_something_with(Trivia.fact.facts)
    

    Or, if you're only going to use that one value:

    from Trivia.fact import facts
    
    do_something_with(facts)
    

    If you want to install all of this as a package so you can run it from anywhere, you will also have to learn about packages, and maybe the import path, but don't worry about that until it's clear you need it.


    All this assumes there's some advantage to storing your data in a Python file --- like it's a list of objects that took a bit of work to initialize. If it's just "raw" data like strings, then a plain text file with one string per line might be the way to go... and you'd be back to using open and probably readlines or for line in ...:.

    "Nearly-raw" data like tables, dictionaries of numbers and strings, or lists of lists can be read and written with either the json or csv modules, depending on how complex your data is and which format you're more comfortable with.