Record#
Today I learned about splitting files and importing files.
When the code becomes too long, we should consider splitting it into different files. Different files can be called and imported using import filename
, and there is no need to input the .py
extension here. To facilitate calling, we can also assign aliases to the imported files using the syntax import filename as alias
.
After importing the file, we can call functions using either filename.functionname
or alias.functionname
.
Today's exercise is to split the previous code into separate files, and then import and call them.
When calling between different files, there is also the issue of passing parameters. This part may not be well understood yet and requires more attention in future learning.
CODE#
## main.py
import os, time, myLibary as lib
try:
f=open("gamelist.txt","r")
gamelist=eval(f.read())
f.close
except:
gamelist = []
while True:
time.sleep(1)
os.system("clear")
print("🌟RPG Inventory🌟")
menu=input("1: Add\n2: Remove\n3: View\n")
if menu == "1":
lib.gameadd(gamelist)
elif menu == "2":
lib.gameremove(gamelist)
elif menu == "3":
lib.gameview(gamelist)
else:
print("input error")
f=open("gamelist.txt","w")
f.write(str(gamelist))
f.close()
### myLibaty.py
def gameadd(gamelist):
gname = input("Input the item to add: > ").capitalize()
gamelist.append(gname)
print(f"{gname} has been added to your inventory.")
def gameremove(gamelist):
if gamelist:
gname=input("Input the item to remove: > ").capitalize()
if gname in gamelist:
gamelist.remove(gname)
print(f"{gname} has been removed from your inventory.")
else:
print(f"{gname} is not in the list.")
else:
print("The list is empty")
def gameview(gamelist):
if gamelist:
gname=input("Input the item to view: > ").capitalize()
if gname in gamelist:
gamenum = gamelist.count(gname)
print(f"You have {gamenum} {gname}.")
else:
print(f"{gname} is not in the list.")
else:
print("The list is empty")