我正在尝试创建一个字谜程序测验。我要做的一件事情是,有一种集中的方法可以根据用户选择的选项从指定的文件中读取数据,而不必重复代码。但是,当尝试将信息保存到文件时,保存的变量将路径文件保存在其中。如何拆分它,使其仅保存已打开的文件的名称(即测验的名称)?
def main():
name = input("Please Enter your name to begin")
print("Hi",name,"Welcome to the Computer Science Quiz")
user_choice = menu()
option = choice(user_choice)
option, counter = questions(option)
update_file(name, option, counter)
def menu():
print("Select from the following categories:")
print("1 for System's Architecture, 2 for Memory, 3 for Storage or 4 for Network Topologies")
choice = int(input("choose option"))
if choice >0 and choice<=4: ## range check
print("you have chosen",choice,)
else:
print("This is an invalid number")
menu()
return choice
def choice(user_choice):
if user_choice == 1:
systems = open('systems.csv','r')
return systems
elif user_choice ==2:
memory = open('memory.csv','r')
return memory
else:
storage = open('storage.csv','r')
return storage
def questions(option):
counter = 0
for line in option:
anagrams = (line.rstrip("\n").split(","))
question = anagrams[0]
answer = anagrams[1]
print (question)
print (answer)
guess = input("Enter your guess")
if guess == answer:
print("Well Done")
counter = counter + 1
else:
print("oops")
print("You have scored",counter,"correctly")
return option,counter
def update_file(name, option, counter):
string_counter = (str(counter))
string_option = (str(option))
results = [name,",",string_counter,",",string_option,"\n"]
file = open('results.csv','a')
file.writelines(results)
file.close()
这是为选项变量保存文件时显示的内容: <_io.TextIOWrapper名称='storage.csv'模式='r'编码='cp1252'>
答案 0 :(得分:1)
您可以使用以下功能从文件名中删除路径:
import os
print(os.path.basename(file_name_with_path))