Splitting a Python Filename [duplicate] - python

This question already has answers here:
Extract file name from path, no matter what the os/path format
(22 answers)
Closed 4 years ago.
I am trying to create an anagram program quiz. One of the things I have done is having one central method of reading from a specified file dependant on which option the user has chosen rather than having to repeat the code. However, when trying to save the info to file, the variable saved has the pathfile saved inside it. How can I split it so that it will only save the name of the file (i.e, name of the quiz) that has been opened?
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()
This is what it shows when the file is saved for the option variable:
<_io.TextIOWrapper name='storage.csv' mode='r' encoding='cp1252'>

You can remove the path from filename with this function:
import os
print(os.path.basename(file_name_with_path))

Related

Export quiz result to a text file in Python

Is it possible to have questions and answers exported to a text file such as result.txt?
I answer all the questions and at the end - all the information is saved in a txt file as a list, that can be viewed later.
Example:
Question 1
Answer 1
Question 2
Answer 2
...
I was wondering about file=open, but would that be right?
And how do I export input questions with file open?
I hope you can help.
from datetime import date
today = date.today()
date = today.strftime("%d.may, %Y.year\n")
print("Today is:", date)
print("Greeting text 1")
print("Greeting text 2\n")
def Vide():
while True:
name = input("Let's see!\nWhat is your name? ")
description = input("Enter a description of the environmental pollution: ")
city = input("In which city is environmental pollution observed? ")
address = input("Enter your residential address: ")
try:
question = int(input("Do you have any additional complaints?\nAnswer with: 1 = Yes, 2 = No\n" ))
except ValueError:
print("Answer with numbers - 1 or 2!")
continue
if question == 1:
print("\nJYou noted that there are additional complaints, fill in the questions again!\n")
continue
elif question == 2:
print("Thank you for your complaint, it will be resolved! 💜")
break
else:
print("Only numbers 1 and 2 are allowed!")
Vide()
As you wanted the file content as a key-value pair, initialize a dictionary and add the corresponding values, instead of using separate variables for names, descriptions, etc. use them as dictionary keys.
First, initialize a global dictionary
global mydict
Initialize it in Vide() function. (use of global keyword because mydict is being modified in a function)
global mydict
mydict = {}
Store question and answer as a key-value pair
mydict["name"] = input("Let's see!\nWhat is your name? ")
mydict["description"] = input("Enter a description of the environmental pollution: ")
mydict["city"] = input("In which city is environmental pollution observed? ")
mydict["address"] = input("Enter your residential address: ")
In try block:
mydict["question"] = int(input("Do you have any additional complaints?\nAnswer with: 1 = Yes, 2 = No\n"))
Now the if-else statements:
if mydict["question"] == 1:
print("\nJYou noted that there are additional complaints, fill in the questions again!\n")
continue
elif mydict["question"] == 2:
print("Thank you for your complaint, it will be resolved! 💜")
break
else:
print("Only numbers 1 and 2 are allowed!")
After calling the function Vide(), write your dictionary to a file
with open("qna.txt", "w") as f:
f.write(str(mydict))
f.close()
Whole code
global mydict
print("Greeting text 1")
print("Greeting text 2\n")
def Vide():
global mydict
mydict = {}
while True:
mydict["name"] = input("Let's see!\nWhat is your name? ")
mydict["description"] = input("Enter a description of the environmental pollution: ")
mydict["city"] = input("In which city is environmental pollution observed? ")
mydict["address"] = input("Enter your residential address: ")
try:
mydict["question"] = int(input("Do you have any additional complaints?\nAnswer with: 1 = Yes, 2 = No\n"))
except ValueError:
print("Answer with numbers - 1 or 2!")
continue
if mydict["question"] == 1:
print("\nJYou noted that there are additional complaints, fill in the questions again!\n")
continue
elif mydict["question"] == 2:
print("Thank you for your complaint, it will be resolved! 💜")
break
else:
print("Only numbers 1 and 2 are allowed!")
Vide()
with open("qna.txt", "w") as f:
f.write(str(mydict))
f.close()
This can be done by writing or appending to a text file. You are correct, we can use the file = open structure to achieve this. I suggest writing something like the following:
file = open('results.txt', 'w')
Then use the following to write to the file once it has been opened.
file.write("Use your variables and questions from before to print user entered data")
Don't forget to close the file once you're done!
file.close()

is it possible to save a float value in a variable even after exiting the script [duplicate]

This question already has answers here:
Keep persistent variables in memory between runs of Python script
(8 answers)
Closed 3 years ago.
Im trying to save a variable so that when I run the script the le can be changed however I also want it to save the current value so that when I close the script and run it again, it should show the last value that was stored in that variable. Basically like a "score" variable.
I don't even know how to start because I have very limited knowledge about python.
import random
import time
import keyboard
import sys
token = 10
yourage = int(input("\033[1;36;40mWhat is your age?: "))
numbers = [1, 2, 3, 4, 5, 6]
def auth():
if yourage >= 18:
print("\nWelcome to the DIE GAME, Your objective is to try to guess the random generated number. If you manage to do so you will win 10 tokens, however if you lose you will lose 2 tokens. The numbers are between 1-6 \n")
roll()
else:
print("You can not enter")
return
def roll():
global token
while token == 0:
print("You can no longer play!")
sys.exit()
return
time.sleep(1.7)
x = int(input("\033[1;36;40mEnter your guess: "))
if x in numbers:
print("The die is rolling...")
time.sleep(2)
temp = random.choice(numbers)
print(temp)
if temp == x:
token = token + 10
print("You guessed right! \n")
print("\033[1;32;40mYour token amount is: ", token)
print("\033[1;37;40m")
again()
return
else:
token = token - 2
print("You guessed wrong :( \n")
print("\033[1;31;40mYour token amount is: ", token)
print("\033[1;37;40m")
again()
else:
print("Your number must be between 1-6, try again")
roll()
def again():
roll()
What Im expecting is that the variable "Token" should save the value of it after the script and when running it in a new window it should show the last value before exiting the script instead of "10".
import os
# Insert code at beginning of script to load score from backup
dir_path = 'C:/Desktop/'
back_up = os.path.join(dir_path, 'backup.txt')
if os.path.isfile(back_up):
with open(back_up, 'r') as r:
score = r.read()
else:
score = open(back_up, 'w+')
# Insert code at end of script to save score to backup
with open(back_up, 'w') as w:
w.write(score)

Getting my Python program to run Power Shell Script

Hello please forgive me if my question duplicate, I've searched previous questions and nothing seems to be quite the same. I'm working on a program that will scan a specific folder and search for specific file types to create a menu for a user to select. Once the user select the menu option the the corresponding file which is a power shell script. Currently My program does everything but run even a simple power shell script. I've attempted several configuration and it's not working. It would be great if someone can see what I may be doing wrong or provide me with some pointers. Code below.
##Text Menu Dynamic test
##version 1
## Created By Dragonshadow
## Code produce in Notpad++ For python v3.4.4
import os
import subprocess
import time
import pathlib
import logging
import fnmatch
import re
## Directory Enumerator
fileFolderLocationFilter = fnmatch.filter(os.listdir('C:\\Users\\myfolder\\Documents\\Automation_Scripts\\ENScripts\\'),"*.ps1")
selectedFile=""
## Menu defined setting veriables
def ENOC_menu():
files = fileFolderLocationFilter
counter = 1
print (20 * "=" , "Enoc Quick Menu" , 20 * "=")
enumFiles = list(enumerate(files))
for counter, value in enumFiles:
str = repr(counter) + ") " + repr(value);
print(str)
str = repr(counter+1) + ") Exit";
print(str)
print (57 * "_")
str = "Enter your choice [1 - " + repr((counter+1)) + "]:"
choice = int(input("Please Enter a Selection: "))
selectedFiles = enumFiles[choice]
return(selectedFiles[1])
if choice > counter :
choice = -1
elif choice != counter :
print("Please selecte a valid choice")
else:
selectedFiles = enumFiles[choice]
print(selectedFiles[1])
##selectedFiles = selectedFiles[1]
return choice
def you_sure():
opt = input("Are you sure Yes or No: ")
if opt=="Yes":
print("Continuing please wait this may take a moment...")
elif opt=="No":
print("returnig to Enoc Menu")
else: ##Stays in loop
print ("Please choose yes or no")
##count_down
def count_down ():
count_down = 10
while (count_down >= 0):
print(count_down)
count_down -= 1
if count_down == 0:
print("Task will continue")
break
##initiating loop
loop = True
while loop:
choice = ENOC_menu()
print ("\n" +"You selected "+ choice +"\n")
subprocess.call("C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\powershell.exe" + choice, shell=True)
##print ("---" +str(selectedFile))
You have probably already figured this out, but I the problem is in the subprocess.call() line. You are concatenating the powershell.exe path and the target file name together. See here:
>>> scriptToRun = "c:\\users\\Username\\Documents\\WindowsPowerShell\\classtestscript.ps1"
>>> powershellExe = "c:\\windows\\system32\\windowspowershell\\v1.0\\powershell.exe"
>>> print(powershellExe + scriptToRun)
c:\windows\system32\windowspowershell\v1.0\powershell.exec:\users\Username\Documents\WindowsPowerShell\classtestscript.ps1
Above, the two strings are stuck together without a space between them. Windows can't make sense of what you're trying to execute.
Put a space between the two two and subprocess.call() will understand what you're trying to do:
>>> print(powershellExe + ' ' + scriptToRun)
c:\windows\system32\windowspowershell\v1.0\powershell.exe c:\users\Username\Documents\WindowsPowerShell\classtestscript.ps1

Python pickles not storing data

I am trying to create a registrar system through Python with pickles. I have gotten the system to record user input, but it does not save it for future implementations of the program.
Here is the code that will start the program:
import datetime
import pandas as pd
import pickle as pck
import pathlib
from pathlib import *
from registrar import *
prompt = "Please select an option: \n 1 Create a new course \n 2 Schedule a new course offering \n 3 List this school's course catalogue \n 4 List this school's course schedule \n 5 Hire an instructor \n 6 Assign an instructor to a course \n 7 Enroll a student \n 8 Register a student for a course \n 9 List this school's enrolled students \n 10 List the students that are registered for a course \n 11 Submit a student's grade \n 12 Get student records \n 13 Exit"
farewell = "Thank you for using the Universal University Registrar System. Goodbye!"
print ("Welcome to the Universal University Registration System.")
print ("\n")
try: #As long as CTRL-C has not been pressed, or 13 not been input by user.
input_invalid = True
while input_invalid:
inst = input("Please enter the name of your institution. ").strip()
domain = input("Please enter the domain. ").strip().lower()
if inst == "" or domain == "":
print("Your entry is invalid. Try again.")
else:
input_invalid = False
schoolie = Institution(inst, domain)
if Path(inst + '.pkl').exists() == False:
with open(inst + '.pkl', 'r+b') as iptschool:
schoolie = pck.load(iptschool)
while True:
print (prompt)
user_input = input("Please enter your choice: ")
try:
user_input = int(user_input)
if user_input < 1 or user_input > 14: #UserInput 14: on prompt.
raise ValueError("Please enter a number between 1 and 13, as indicated in the menu.")
except ValueError:
print("Not a valid number. Please try again.")
if user_input == 1: #Create a new course
input_invalid2 = True #Ensure that the user actually provides the input.
while input_invalid2:
input_name = input("Please enter a course name: ").strip()
input_department = input("Please enter the course's department: ").strip()
input_number = input("Please enter the course's number (just the number, not the departmental prefix): ").strip()
try:
input_number = int(input_number)
except ValueError:
print ("Please print an integer. Try again.")
input_credits = input("Please enter the number of credits awarded for passing this course. Please use an integer: ").strip()
try:
input_credits = int(input_credits)
except ValueError:
print ("Please print an integer. Try again.")
if input_name != "" and input_department != "" and input_number and input_credits:
input_invalid2 = False #Valid input
else:
print("One or more of your entries is invalid. Try again.")
added_course = Course(input_name, input_department, input_number, input_credits)
for course in schoolie.course_catalog:
if course.department == input_department and course.number == input_number and course.name == input_name:
print("That course is already in the system. Try again.")
input_invalid2 == True
if input_invalid2 == False:
schoolie.add_course(added_course)
print ("You have added course %s %s: %s, worth %d credits."%(input_department,input_number,input_name, input_credits))
And here is the second option, which SHOULD reveal that it is stored, but it does not.
elif user_input == 2: #Schedule a course offering
input_invalid2 = True #Ensure that the user actually provides the input.
while input_invalid2:
input_department = input("Please input the course's department: ").strip()
input_number = input("Please input the course's number: ").strip()
course = None
courseFound = False
for c in schoolie.course_catalog:
if c.department == input_department and c.number == input_number: #Course found in records
courseFound = True
course = c
input_section_number = input("Please enter a section number for this course offering: ").strip()
input_instructor = input("If you would like, please enter an instructor for this course offering: ").strip()
input_year = input("Please enter a year for this course offering: ").strip()
input_quarter = input("Please enter the quarter in which this course offering will be held - either SPRING, SUMMER, FALL, or WINTER: ").strip().upper()
if input_course != "" and input_course in schoolie.course_catalog and input_section_number.isdigit() and input_year.isdigit() and input_quarter in ['SPRING', 'SUMMER', 'FALL', 'WINTER'] and input_credits.isdigit():
if input_instructor != "": #Instructor to be added later, if user chooses option 6.
added_course_offering = CourseOffering(c, input_section_number, None, input_year, input_quarter)
else:
added_course_offering = CourseOffering(c, input_section_number, input_instructor, input_year, input_quarter)
schoolie.add_course_offering(added_course_offering)
input_invalid2 = False #Valid input
print ("You have added course %s, Section %d: %s, worth %d credits."%(input_course,input_section_number,input_name, input_credits))
else:
print("One or more of your entries is invalid. Try again.")
if courseFound == False: #If course has not been found at the end of the loop:
print("The course is not in our system. Please create it before you add an offering.")
break
By the way, I think I have the system closing properly. Correct me if I'm wrong:
elif user_input == 13: #Exit
with open(inst + '.pkl', 'wb') as output:
pck.dump(schoolie, output, pck.HIGHEST_PROTOCOL)
del schoolie
print (farewell)
sys.exit()
except KeyboardInterrupt: #user pushes Ctrl-C to end the program
print(farewell)
I believe that there is something wrong with the way that I am setting up the pickles files. I'm creating them, but I seem not to be putting data into them.
I apologize for the long-winded nature of this question, but I hope that the details will help you understand the problems that I've been having. Thanks in advance for the help!
it seems you may have dump and load reversed: (from the docs)
Signature: pck.load(file, *, fix_imports=True, encoding='ASCII', errors='strict')
Docstring:
Read and return an object from the pickle data stored in a file.
Signature: pck.dump(obj, file, protocol=None, *, fix_imports=True)
Docstring:
Write a pickled representation of obj to the open file object file.
With all those lines of code, it does get a little confusing, but I don't see any code that is pickling and writing the objects to a file.
Before anything else, you should assign the file to a variable so you can reference it. To do this, you'll have code similar to this:MyFile = open("FileName.extension","wb"). MyFile can be any name you want, it will be what you use later to reference the file. FileName is the name of the file itself. This is the name it will have in File Explorer. .extension is the file's extension, specifying the type of file. You should use .dat for this. wb is the file access mode. "w" means write, and "b" means binary. (Pickled objects can only be stored in a binary file.)
To write the pickled objects, you'll need this code:pck.dump(object,MyFile). (Usually, you would use pickle.dump(object,MyFile), but you imported pickle as pck.)
After writing the data to the file, you'll want to retrieve it. To do this, the "wb" instance of MyFile needs to be closed like this:MyFile.close(). Then you'll need to re-open the file in read mode using the following code:MyFile = open("FileName.extension","rb") Then you would use this:object = pickle.load(MyFile) to read the data. In the preceding example, (the load function), your object must have the same name as when you pickled it using the dump function. (pck.dump(object,MyFile))
In the end, you'll end up with something similar to this:
if writing conditions are true:
MyFile = open("FileName.dat","wb")
pickle.dump(object,MyFile) # This will be repeated for each object.
MyFile.close()
if reading conditions are true:
MyFile = open("FileName.dat","rb")
object = pickle.load(MyFile) # This will be repeated for each object.
MyFile.close()
I'm sorry if this wasn't the answer you wanted. Because of all those lines of code, it is somewhat hard to understand. I need clarification to give a better answer.

How do I allow only the latest inputs to be saved - Python

How do I implement a simple code that will only save the student's latest 3 scores? If the test is repeated later, the old score should be replaced.
Thank you.
This is the code that asks the user the questions and saves the results in the txt. files.
import random
import math
import operator as op
correct_answers = 0
def test():
num1 = random.randint(1, 10)
num2 = random.randint(1, 10)
ops = {
'+': op.add,
'-': op.sub,
'*': op.mul,
}
keys = list(ops.keys())
rand_key = random.choice(keys)
operation = ops[rand_key]
correct_result = operation(num1, num2)
print ("What is {} {} {}?".format(num1, rand_key, num2))
user_answer= int(input("Your answer: "))
if user_answer != correct_result:
print ("Incorrect. The right answer is {}".format(correct_result))
return False
else:
print("Correct!")
return True
username = input("What is your name? ")
print("Hi {}! Welcome to the Arithmetic quiz...".format(username))
class_name = input("Are you in class 1, 2 or 3? ")
correct_answers = 0
num_questions = 10
for i in range(num_questions):
if test():
correct_answers +=1
print("{}: You got {}/{} questions correct.".format(
username,
correct_answers,
num_questions,
))
class_name = class_name + ".txt" #creates a txt file called the class that the user entered earlier on in the quiz.
file = open(class_name , 'a') #These few lines open and then write the username and the marks of the student into the txt file.
name = (username)
file.write(str(username + " : " ))
file.write(str(correct_answers))
file.write('\n') #This puts each different entry on a different line.
file.close() #This closes the file once the infrmation has been written.
A much better solution would be to store the data in a different format that made everything easy. For example, if you used a shelve database that mapped each username to a deque of answers, the whole thing would be this simple:
with shelve.open(class_name) as db:
answers = db.get(username, collections.deque(maxlen=3))
answers.append(correct_answers)
db[username] = answers
But if you can't change the data format, and you need to just append new lines to the end of a human-readable text file, then the only want to find out if there are already 3 answers is to read through every line in the file to see how many are already there. For example:
past_answers = []
with open(class_name) as f:
for i, line in enumerate(f):
# rsplit(…,1) instead of split so users who call
# themselves 'I Rock : 99999' can't cheat the system
name, answers = line.rsplit(' : ', 1)
if name == username:
past_answers.append(i)
And if there were 3 past answers, you have to rewrite the file, skipping line #i. This is the really fun part; text files aren't random-access-editable, so the best you can do is either read it all into memory and write it back out, or copy it all to a temporary file and move it over the original. Like this:
excess_answers = set(past_answers[:-2])
if excess_answers:
with open(class_name) as fin, tempfile.NamedTemporaryFile() as fout:
for i, line in enumerate(fin):
if i not in excess_answers:
fout.write(line)
os.replace(fout.name, fin)
That part is untested. And it requires Python 3.3+; if you have an earlier version and are on Mac or Linux you can just use os.rename instead of replace, but if you're on Windows… you need to do some research, because it's ugly and no fun.
And now, you can finally just append the new answer, as you're already doing.

Categories

Resources