Externalize the name of the file containing student data.
Requires: python-decouple (pip3 install python-decouple)
First: run gitstudents.py. It works, but the filename is hardcoded.
Not very maintainable.
Let's improve it:
-
create a file named
.envcontaining this:# name of file containing student data CSVFILE = "students.csv" -
In
gitstudents.py, add:from decouple import config
-
And read the filename from the configuration file (.env):
datafile = config('CSVFILE') data = open(datafile)
-
Run the code. It should still work.
- You can rename the file (and change .env) and it still works -- no need to modify code.
-
Externalize the number of students to print (10). In
.envadd:count = 10In the Python code:
count = config('count', default=10, cast=int)
cast=intmeans to convert the value toint; the default is to return the value as a string. -
Run it. It should still work. But now you want to print 20 students.
-
In
.envchange the value ofcountto 20. Run the code again. Does it work?
Python-decouple Doc: https://pypi.org/project/python-decouple/
How to Use Decouple: https://simpleisbetterthancomplex.com/2015/11/26/package-of-the-week-python-decouple.html