Print items from a list in an external .py file
<p>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 <code>facts</code>with some items on it but how can I read the items from that list? It goes something like</p>

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

<p>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.</p>

<p><code>open</code> is for files containing data; files containing Python code are typically accessed with <a href="https://docs.python.org/3/reference/import.html" rel="nofollow"><code>import</code></a>.  See <a href="https://docs.python.org/3/tutorial/" rel="nofollow"><em>The Python Tutorial</em></a>'s section <a href="https://docs.python.org/3/tutorial/modules.html#modules" rel="nofollow">6. Modules</a> for the typical use cases.</p>

<p>Assuming you'll always be running your script from the same directory:</p>

<pre><code>import Trivia.fact

do_something_with(Trivia.fact.facts)
</code></pre>

<p>Or, if you're only going to use that one value:</p>

<pre><code>from Trivia.fact import facts

do_something_with(facts)
</code></pre>

<p>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 <a href="https://docs.python.org/3/reference/import.html#packages" rel="nofollow">packages</a>, and maybe the <a href="https://docs.python.org/3/glossary.html#term-import-path" rel="nofollow">import path</a>, but don't worry about that until it's clear you need it.</p>

<hr>

<p>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 <code>open</code> and probably <a href="https://docs.python.org/3/library/io.html#io.IOBase.readlines" rel="nofollow"><code>readlines</code></a> or <code>for line in ...:</code>.</p>

<p>"Nearly-raw" data like tables, dictionaries of numbers and strings, or lists of lists can be read and written with either the <a href="https://docs.python.org/3/library/json.html" rel="nofollow"><code>json</code></a> or <a href="https://docs.python.org/3/library/csv.html#examples" rel="nofollow"><code>csv</code></a> modules, depending on how complex your data is and which format you're more comfortable with.</p>

python list