def add(fm_list):
while True:
msg = input("What do you want to create?: "
"\n Insert 1 for Folder "
"\n Insert 2 for Subfolder.\n")
if msg == "1":
folder = input("Name of the folder: ")
choice = input("Do you want to add a subfolder to this folder?: (y/n): ")
if choice.lower() == "y":
# ... do things ...
break
elif choice == "n":
# ... do things ...
break
else:
print("Please choose between (y/n)\n")
elif msg == "2":
store = input("Where do you want to store your subfolder?: "
"\n Insert A to store it in the DEFAULT folder"
"\n Insert B to store it in a new folder\n")
if store.lower() == "a":
# do things ...
break
elif store.lower() == "b":
# do things ...
break
else:
print("Invalid entry!!!\n")
continue
Thanks in advance for the answers.
I have my function add() here, I would like when I hit the stage of the elif msg == 2... when the user inputs anything else other than the available options (a or b) then he gets prompt back to choose the appropriate option (In other words, I give the hand again and ask the user where to store the subfolder) ... instead it does prompt back at the beginning of the code.
msg = input("What do you want to create?: "
"\n Insert 1 for Folder "
"\n Insert 2 for Subfolder.\n")
...Thanks
Well after some time and some help I finally get to do what I wanted
we created a recursive function (not sure if this is it is called tho) then call it back later on the add function:....
def getstore(fm_list):
store = input("Where do you want to store your subfolder?: "
"\n Insert A to store it in the DEFAULT folder"
"\n Insert B to store it in a new folder\n")
if store.lower() == "a":
subfolder = input("What is the name of the subfolder: ")
fm_list.append(subfolder)
print("Your subfolder will be store to the Default folder: ")
os.chdir('F:\\Test\\Default') # this is the Default folder already in the test directory
os.makedirs(subfolder, exist_ok=True)
print(subfolder + " was added to the folder named Default")
quit()
elif store.lower() == "b":
folder = input("Name of the folder: ")
fm_list.append(folder)
os.chdir('F:\\Test')
os.makedirs(folder, exist_ok=True)
subfolder = input("Name of the subfolder: ")
fm_list.append(subfolder)
os.chdir('F:\\Test\\' + folder)
os.makedirs(subfolder, exist_ok=True)
print(folder + " was added to the list of folder.")
print(subfolder + " was added to " + folder)
quit()
else:
getstore(fm_list)
then later when we get to the elif msg == "2" we call getstore(fm_list)
just like this...
elif msg == "2":
getstore(fm_list)
break
else:
print("Invalid entry!!!\n")
continue
And that's it.
Related
I am relatively new to python and have been working on a simple program that allows the user to view, edit and create new text files. The option I am currently focusing on is creating new text files. The program asks the user various questions, which are then inputted in the text file.
Currently what I am stuck on is, I am trying to technically "list" a bunch of inputs into the text file. So, say the question would be outputted such as:
Enter the amount of dog breeds you could think of:
(USER INPUT)
Jack Russel
(PROGRAM INPUT)
Done? (Y/N)
(USER INPUT)
N
(PROGRAM INPUT)
Continue.
(USER INPUT)
Chihuahua
(PROGRAM INPUT)
Done? (Y/N)
(USER INPUT)
Y
[FINISH]
I have tried to do this by implementing a while loop to ask the user whether they are done or not, and although this works, whenever the user inputs another input, it will overwrite the first one in the text file rather than adding a completely new one. Is there a neat, compact way of doing this, or do I have to create a new function for every "dog breed" that the user inputs?
Code:
keepGoing = True
while keepGoing == True:
dogb = input("Enter a dog breed: ")
dogc = input("Enter the dog colour: ")
dogn = input("Enter the dog name: ")
dogmale = input("Are they male? ")
complete = False
while complete == False:
done = input ("DONE? (Y/N): ")
if done == "Y":
keepGoing = False
complete = True
elif done == "N":
keepGoing = True
complete = True
else:
print ("Invalid Option")
createFile.write("\n" + "Dog Breed: " + dogb + '\n' + "Dog colour: " + dogc + '\n' + "Dog name: " + dogn + " (Male? " + dogmale + ")")
So currently, when my program is run, the user will be prompted with those 4 questions. Once they answer all 4, it will be stored as 4 separate lines in a text file. However, if the user inputs that they are NOT done, implying they want to add another dog breed, it will ask those 4 questions again like I want it to, but when they are answered, it will just overwrite the first inputs. I want to make it so that, if the user inputs that they are not done, when they answer the 4 questions again, it will add another 4 lines of text for the new dog breed they added, until the user inputs "Y" for done, which will stop the loop and continue the program.
I am not sure what to do other than making completely new functions for every single dog breed, but I am sure there is a better, neater way of doing so. Any help would be greatly appreciated, thanks!
EDIT: I would assume it has something to do with appending the new data that I added to the text file rather than overwriting it.
I am having this issue in the first place because I am not sure how to open the file, since I am creating a new one from scratch using this code:
save_path = 'D:/My project/users/'
name_of_file = input("What do you want to name the file? ")
completeName = os.path.join(save_path, name_of_file+".txt")
createFile = open(completeName, "w")
referenceName = input("Enter the name of the dog (e.g. Homer Simpson): ")
and then the data is written to the text file using:
myfile.write(referenceName) etc
Here is your updated code
keepGoing = True
while keepGoing == True:
dogb = input("Enter a dog breed: ")
dogc = input("Enter the dog colour: ")
dogn = input("Enter the dog name: ")
dogmale = input("Are they male? ")
complete = False
while complete == False:
done = input ("DONE? (Y/N): ")
if done == "Y":
keepGoing = False
complete = True
elif done == "N":
keepGoing = True
complete = True
else:
print ("Invalid Option")
with open("test.txt", "a") as myfile:
myfile.write("\n" + "Dog Breed: " + dogb + '\n' + "Dog colour: " + dogc + '\n' + "Dog name: " + dogn + " (Male? " + dogmale + ")")
I'm not sure just how new to Python you are, but a common newbie mistake that creates this exact situation is opening the file with w instead of a.
Points to take care of
Opening a file- you should do it using open it creates the file if doesnot exists and then closes the file.
with open('file.txt', 'w') as f:
f.write("hello world")
In order to take multiple inputs you should have someway(data-structure) to store the value. - list
Updated Solution
keepGoing = True
dogs = [] #added a list, which will store all different inputs,
while keepGoing == True:
dogb = input("Enter a dog breed: ")
dogc = input("Enter the dog colour: ")
dogn = input("Enter the dog name: ")
dogmale = input("Are they male? ")
complete = False
dogs.append({"dogb": dogb, "dogc": dogc,"dogn":dogn, "dogmale": dogmale}) # dictionary, which is appended to list
# so now, in a list each index has data of a dog. So now as many inputs can be handled.
while complete == False:
done = input ("DONE? (Y/N): ")
if done == "Y":
keepGoing = False
complete = True
elif done == "N":
keepGoing = True
complete = True
else:
print ("Invalid Option")
with open('file.txt', 'w') as f:
f.write("hello world")
for dog in dogs: #iterating over the list to write the list to file.
f.write("\n" + "Dog Breed: " + dog["dogb"] + '\n' + "Dog colour: " + dog["dogc"] + '\n' + "Dog name: " + dog["dogn"] + '\n'+" (Male? " + dog["dogmale"] + ")" + '\n')
# createFile.write("\n" + "Dog Breed: " + dogb + '\n' + "Dog colour: " + dogc + '\n' + "Dog name: " + dogn + " (Male? " + dogmale + ")")
I am trying to create a phone book and I have everything except I need to run the entire code over and over instead an individual if statement. I am not sure how to continue any advice?
I have used a while loop.
#Intro
print("Address book to store friends contact")
print("-" * 50)
print("-" * 50)
#Display of options
print("Select an option: ")
print("1-Add/Update contact")
print("2- Display all contacts")
print("3- Search")
print("4- Delete contact")
print("5- Quit")
#Selection
option = input("Select which one you would like to choose. Ex. Select an
option. Type here: ")
#Map
contacts = {}
#Main program
for i in range(0,1):
if option == "Add/Update contact":
person_added = input("Who would you like to be updated or added")
next_question = input("What is there contact information")
#The code below will add the person to the list or update them
contacts [person_added] = next_question
elif option == "Display all contacts":
print(contacts)
elif option == "Search":
search_question = input("Who are you looking for: ")
for search in contacts.items():
if search == search_question:
print("I found" + search)
else:
print("Contact not found")
elif option == "Delete contact":
person_deleted = input("Who would you like to be deleted ")
del(contacts[person_deleted])
else:
print("Thank You! Goodbye")
I am new to Pycharm, and Python as a whole, and for my first project I decided to do a random name/object selector which chooses a name from a pre-made variable of letters and prints that result.
I wanted to expand on this and have the user either use the default names in the code or add their own names to be used.
I gave it my best effort but when it came to the script running 1 of two functions I was unable to figure out how to do that.
Any help?
import string
import random
import os
letters = 'wjsdc' #*Default letters*
choice = random.choice(letters)
decision = input("Hello, use default? y/n")
print("You have chosen " + decision + ", Running function.")
def generator():
if decision == "y": #*Default function*
choice = random.choice(letters)
print("Name chosen is " + generator())
elif decision == "n": #*Attempted new function*
new_name1 = input("Please add a name")
new_name2 = input("Please add a name")
new_name3 = input("Please add a name")
new_name4 = input("Please add a name")
new_name5 = input("Please add a name")
if choice == "w":
finalname = new_name1
elif choice == "j":
finalname = new_name2
elif choice == "s":
finalname = new_name3
elif choice == "c":
finalname = new_name4
elif choice == "d":
finalname = new_name5
name = finalname
return name
print("Name chosen is " + name)
def generator(): #*Default function script*
if choice == "w":
finalname = "Wade"
elif choice == "j":
finalname = "Jack"
elif choice == "s":
finalname = "Scott"
elif choice == "d":
finalname = "Dan"
elif choice == "c":
finalname = "Conall"
name = finalname
return name
print("Name chosen is " + generator())
Your code is pretty weird, and I'm not sure what you are trying to achieve.
you define two functions generator; you should give them different names
instead of chosing from one of the letters and then selecting the "long" name accordingly, just chose from the list of names in the first place
you can use a list for the different user-inputted names
I'd suggest using something like this:
import random
def generate_name():
names = "Wade", "Jack", "Scott", "Dan", "Conall"
decision = input("Use default names? Y/n ")
if decision == "n":
print("Please enter 5 names")
names = [input() for _ in range(5)]
return random.choice(names)
print("Name chosen is " + generate_name())
Very beginner programmer here in the process of learning. I am just wondering if this simple code I have typed is the most optimal way to do it.
with open('guest_book.txt', 'a') as file_object:
while True:
name=input("What is your name?")
print("Welcome " + name + ", have a nice day!")
file_object.write(name + " has visited! \n")
another = input("Do you need to add another name?(Y/N)")
if another == "y":
continue
elif another == "n":
break
else:
print("That was not a proper input!")
while True:
another = input("Do you need to add another name?(Y/N)")
if another == "y":
a = "t"
break
if another == "n":
a = "f"
break
if a == "t":
continue
else:
break
My questions is in the if statements. When I ask the input("Do you need to add another name?(y/n)", is what I have typed the best way to re-ask the question if I get an answer other than y or n. Basically I want the question to be repeated if I don't get either a yes or no answer, and the solution I found does not seem like the most optimal solution.
You are basically there. You can simply:
with open('guest_book.txt', 'a') as file_object:
while True:
name=input("What is your name?")
print("Welcome " + name + ", have a nice day!")
file_object.write(name + " has visited! \n")
another = input("Do you need to add another name?(Y/N)")
if another == "y":
continue
elif another == "n":
break
else:
print("That was not a proper input!")
continue
You can use function to write your all logic at one place.
def calculate(file_object):
name=raw_input("What is your name?")
print("Welcome " + name + ", have a nice day!")
file_object.write(name + " has visited! \n")
another = raw_input("Do you need to add another name?(Y/N)")
if another == "y":
calculate(file_object)
elif another == "n":
return
else:
print("That was not a proper input!")
calculate(file_object)
if __name__=='__main__':
with open('guest_book.txt', 'a') as file_object:
calculate(file_object)
You can do it this way, but there will not be any invalid input for saying no. It will only check for saying y
with open('guest_book.txt', 'a') as file_object:
another = 'y'
while another.lower() == 'y':
name=input("What is your name?")
print("Welcome " + name + ", have a nice day!")
another = input("Do you need to add another name?(Y/N)")
I have some code, which I will rather not share but this a portion
try_again = input ("Try again?")
if answer == "Y" or answer == "y":
clear()
file_path = os.path.dirname(os.path.realpath(__file__))
open file_path + "maze_game.exe"
exit()
else:
exit()
I want the file to open itself (to start at the beginning) I have tested it and it DOES work but, if the user renames the file (unlikely but possable) clearly this wont work unless they decompile, edit, and recompile. so I want to get the name of itself, store that in a variabe and open like this:
file_name = how ever I get the name
try_again = input ("Try again?")
if answer == "Y" or answer == "y":
clear()
file_path = os.path.dirname(os.path.realpath(__file__))
open file_path + file_name
exit()
else:
exit()
so how might I get the file name?
EDIT: here is my whole code:
import os
import time
clear = lambda: os.system('cls')
name = input ("What is your name? ")
friend = "Charels"
if name == "Charels" or name == "charels" or name == "Charles" or name == "charles":
friend = "Chuck"
print ("Welcome to the Maze Game Dr. " + name)
time.sleep(1.5)
clear()
print ("No one has made it out of Colwoods' labrynth,\nhowever there are rumours of untold riches at the end. \nThe most recent victim of the Maze is your best friend, " + friend)
time.sleep(1.5)
clear()
print ("Are you sure you want to continue?")
answer = input ("Y or N? ")
if answer == "Y" or answer == "y":
("")
else:
friend = friend + " for dead. R.I.P."
print ("Shame on you, you left " + friend)
time.sleep(1.5)
clear()
print ("YOU LOSE")
time.sleep(1.5)
clear()
file_name = how ever I get the name
try_again = input ("Try again?")
if answer == "Y" or answer == "y":
clear()
file_path = os.path.dirname(os.path.realpath(__file__))
open file_path + file_name
exit()
else:
exit()
input ("...")
no, the program is not completed and ignore the last line
Maybe I am misunderstanding what you want, but I think os.path.basename(__file__) will do the trick.
This will give you just the file part of your path, so if you have a filefoo/bar/baz.py and pass that path like os.path.basename('foo/bar/baz.py'), it will return the string 'baz.py'.
So try:
file_name = os.path.basename(__file__)
That being said, your approach seems a little atypical as #Blender points out, and I have never tried to have a program restart itself in this way. I am not sure if this answer will make your program work correctly, but it will give you the name of the file that is running your program, which seems to be what you are looking for.