Python Use Dictionary List? What Do I Use - python

I am making a type of quiz, and want to know how to compare the results to a text file. After answering the questions with prompted input, the function will return a four digit code. I want that four digit code to be compared to "truecode" in a text file I've written out with additional information like this:
villagername,personality,birthday,zodiac,truecode,species
Ankha,snooty,September 22nd,Virgo,A420,Cat
Bangle,peppy,August 27th,Virgo,A330,Tiger
Bianca,peppy,December 13th,Sagittarius,A320,Tiger
Bob,lazy,January 1st,Capricorn,A210,Cat
Bud,jock,August 8th,Leo,A310,Lion
I want this other information to be printed out.
print("Your villager is " + villagername)
print("They are a " + personality + " type villagers and of the " + species + " species.")
print("Their birthday is " + birthday + " and they are a " + zodiac)
print("I hope you enjoyed this quiz!")
I cannot figure out how to extract this information and compare it to what I have. Should I use a list or a dictionary? I'm getting frustrated trying to Google my question and wondering if I went around it all wrong.
How do I compare the four digit code (that will be returned from another function) to "true code" and get everything spit out like above?

import csv
def compare_codes(true_code):
with open(''file.txt) as csvfile:
details_dict = csv.reader(csvfile)
for i in details_dict:
if i['truecode'] == tru_code:
print("Your villager is:",i['villagername'])
print("They are a " + i['personality'] + " type villagers and of the " + i['species'] + " species.")
print("Their birthday is " + i['birthday'] + " and they are a " + i['zodiac'])
print("I hope you enjoyed this quiz!")
break
compare_codes('A420')
Above code reads the text file and compares the input with truecode value in your file and displays the info.

import csv
def get_data(filename):
with open(filename) as f:
reader = csv.DictReader(f, delimiter=',')
data = {row['truecode']: row for row in reader}
return data
def main():
filename = 'results.txt'
data = get_data(filename)
code = input('Enter code: ')
try:
info = data[code]
print("Your villager is " + info['villagername'])
print("They are a " + info['personality'] +
" type villagers and of the " + info['species'] + " species.")
print("Their birthday is " +
info['birthday'] + " and they are a " + info['zodiac'])
print("I hope you enjoyed this quiz!")
except KeyError:
print('Invalid code')
if __name__ == "__main__":
main()

The type of file that you have is actually called a CSV file. If you wanted to, you could open your text file with any spreadsheet program, and your data would show up in the appropriate cells. Use the csv module to read your data.
import csv
def get_quiz_results(truecode):
with open('your-text-file.txt') as csvfile:
csvreader = csv.reader(csvfile)
for row in csvreader:
# row is a dictionary of all of the items in that row of your text file.
if row['truecode'] == truecode:
return row
And then to print out the info from your text file
truecode = 'A330'
info = get_quiz_results(truecode)
print("Your villager is " + info["villagername"])
print("They are a " + info["personality"] + " type villagers and of the " + info["species"] + " species.")
print("Their birthday is " + info["birthday"] + " and they are a " + info["zodiac"])
print("I hope you enjoyed this quiz!")
When looping over the file, the csv module will turn each line of the file into a dictionary using the commas as separators. The first line is special, and is used to create the dictionary keys.

Related

Is there a way to not delete the user input in a text file after running it again?

Whenever I run this program it will ask for a username and a password, store them as the first values in the two lists, open up a text file, and then write password: and username: then whatever username_Database[0] and password_Database[0] are. The problem is when I run the program again, it deletes the previous values. Is there anyway to save the user input and not have it deleted when I run the program again?
import time
username_Database = []
password_Database = []
username = input("Enter a username\n")
username_Database.append(username)
password = input("Enter a password\n")
password_Database.append(password)
print('You are now registered and your user name is \n' + username_Database[0] + "\n and your password is \n" + password_Database[0] + "\n")
print("Saving...")
filename = open("data.txt", "w")
filename.add("Password: " + str(password_Database[0] + "\n"))
filename.add("Username: " + str(username_Database[0] + "\n"))
time.sleep(2)
exit()
You are using write mode when opening the file, it will overwrite everything inside the file. Change it to append mode.
# Using append mode
filename = open("data.txt", "a")
# It should be write instead of add
filename.write ("Password: " + str(password_Database[0] + "\n"))
filename.write ("Username: " + str(username_Database[0] + "\n"))

Appending to a file error - PYTHON

Please bear with my as I am new to python and am learning by creating simple programs. Recently I started making my own program that generates a file and allows the user to choose things and store them in each file. In this example I was going for a song playlist generator. Although it was difficult I soldiered through until I came across this error that I couldn't fix. It was with the opening of a file.
This is the Code
cont = "0"
log = 0
data = open("songs.txt", "r")
songs = data.readlines()
songs.sort()
while log < 20:
cont = input("Do you want to make a playlist? [Yes or No]")
while cont == "yes":
print ("1. ", songs[0],"2. ", songs[1],"3. ", songs[2],"4. ", songs[3],"5. ", songs[4],"6. ", songs[5],"7. ", songs[6],"8. ", songs[7],"9. ", songs[8],"10. ", songs[9],"11. ", songs[10],"12. ", songs[11],"13. ", songs[12],"14. ", songs[13],"15. ", songs[14],"16. ", songs[15],"17. ", songs[16],"18. ", songs[17],"19. ", songs[18],"20. ", songs[19])
new = "playlist" + str(log) + ".txt"
print(new)
log = log + 1
cont = "no"
choice = int(input("Please enter the first choice of song you would like in your playlist [Type the allocated number please]"))
choice1 = choice - 1
"playlist" + str(log) + ".txt".append(songs[choice1])
However, my code is supposed to allow the user to choose songs from my print function and then add them to the playlist generatored and then repeat this for as many playlists they want. Now my code is giving me an error message.
File "playlists.py", line 18, in <module>
"playlist" + str(log) + ".txt".append(songs[choice1])
AttributeError: 'str' object has no attribute 'append'
What is this Error stating and also how can I overcome it.
Thanks in advance and anticipation!
The issue is that this line:
"playlist" + str(log) + ".txt".append(songs[choice1])
is just super wrong/sort of like pseudocode. To append to a text file requires you open it for appending and then write to it. Do this like so:
with open("playlist" + str(log) + ".txt", "a") as myfile:
myfile.write(str(songs[choice1]))

Python: Attempting to append to file but nothing is being written

This section of code should write an input and another variable (Score) to a text file. The program asks for the input (so the if statement is definitely working) and runs without errors, but the text file is empty. Oddly, copying this code to an empty python file and running it works without errors. What is happening here?
if Score > int(HighScores[1]):
print("You beat the record with " + str(Score) + " points!")
Name = input("What is your name?")
BestOf = open("High Scores.txt", "w").close()
BestOf = open("High Scores.txt", "a")
BestOf.write(Name + "\n")
BestOf.write(str(Score))
I didn't close the file after appending.
BestOf.close()
fixed it
Try opening the file in 'w+' mode. This will create the file if it doesn't exist.
You can also check if the file exits using the 'os' module.
import os;
if Score > int(HighScores[1]):
print("You beat the record with " + str(Score) + " points!")
name = input("What is your name?")
if os.path.isfile("Scores.txt"):
fh = open("Scores.txt", "a")
else:
fh = open("Scores.txt", "w+")
fh.write(name + "\n")
fh.write(str(Score))
fh.close()

Python: Running multi variables using the same function at the same time. New to Python

I've been working with python for the past few days, and started working on a project. Currently trying to figure out how to execute the same function using multiple variables (In this case, Stock symbols). Preferably with one input() separated with a comma or something. I've hit a snag with this last part though. Can anyone point me in the direction of where to go next? (Running the same function with multiple variables at the same time.)
Here is my code:
#Google + Yahoo Finance Stock Lookup
from googlefinance import getQuotes
from yahoo_finance import Share
import googlefinance
import datetime, time
import os
from datetime import datetime
tDate = datetime.now().strftime('%Y-%m-%d')
print (tDate)
tDateConv = str(tDate)
try:
os.chdir('/Users/Jakes_Macbook/Desktop/Python/Stocks')
except Exception:
print('Default Path does not exsist, make sure your directory is right.')
pass
run = True
while run == True:
print('You are currently storing the file in ')
print(os.getcwd())
print('type "yes" to continue')
confirm = input()
if confirm == 'yes':
print ('ok\n')
try:
os.makedirs(tDateConv)
except Exception:
pass
os.chdir(tDateConv)
print('File will be saved to:')
print(os.getcwd())
break
else:
print('Where do you want to store the file?')
changeDir = input()
os.chdir(changeDir)
print('What Stock or Stocks would you like to look up?')
stockSymbol = input()
def runStocks():
print (" ")
print ("Stock Symbol: " + stockSymbol)
stockSymbolYhoo = Share(stockSymbol)
stockFile = open(str(stockSymbol)+'.txt', 'a')
dicStored = googlefinance.getQuotes(stockSymbol)[0]
numStoredPrice = float(dicStored['LastTradePrice'])
print('Stock Open: ' + stockSymbolYhoo.get_open())
print ("Stored Price: " + str(numStoredPrice))
stockFile.write(str("\n" + "Stock Symbol: " + stockSymbol + "\n"))
stockFile.write(str("\n" + "Open Price: " + stockSymbolYhoo.get_open() + "\n"))
stockFile.write(str("Stored Price: " + str(numStoredPrice)+'\n'))
runs = 0
while runs < 5:
stor = googlefinance.getQuotes(stockSymbol)[0]
price = stor['LastTradePrice']
print(str(datetime.now().strftime('%Y-%m-%d %H:%M:%S')) + " | " + price)
stockFile.write(str(datetime.now().strftime('%Y-%m-%d %H:%M:%S')) + " | Price " + price + ' \n')
numPrice = float(price)
if numPrice < numStoredPrice*float(.995):
print ("buy")
time.sleep(5)
runs = runs + 1
stockFile.close()
runStocks()
My goal is to have each stock symbol, that is inputted, create its own file in the folder for today. I'm pretty sure i can figure out how to do that once i get multiple functions going. Thanks in advance.
Also, let me know if you have any important suggestions or best practices. This is like my second day working with python. Thanks Again.
Just pass them into the function:
# Note the definition was updated to be able to pass in a stockSymbol
def runStocks(stockSymbol):
print (" ")
print ("Stock Symbol: " + stockSymbol)
stockSymbolYhoo = Share(stockSymbol)
stockFile = open(str(stockSymbol)+'.txt', 'a')
dicStored = googlefinance.getQuotes(stockSymbol)[0]
numStoredPrice = float(dicStored['LastTradePrice'])
print('Stock Open: ' + stockSymbolYhoo.get_open())
print ("Stored Price: " + str(numStoredPrice))
stockFile.write(str("\n" + "Stock Symbol: " + stockSymbol + "\n"))
stockFile.write(str("\n" + "Open Price: " + stockSymbolYhoo.get_open() + "\n"))
stockFile.write(str("Stored Price: " + str(numStoredPrice)+'\n'))
stockSymbols = input("Enter stock symbols separated by commas").split(",")
for stockSymbol in stockSymbols:
runStocks(stockSymbol) # Call your function in a loop

python wont write even when I use f.close

I'm trying to write some code that outputs some text to a list. output is a variable that is a string which is the name of the file to be written. However whenever I look at the file nothing is written.
with open(output, 'w') as f:
f.write("Negative numbers mean the empty space was moved to the left and positive numbers means it was moved to the right" + '\n')
if A == True:
the_h = node.h
elif A== False:
the_h = 0
f.write("Start " + str(node.cargo) + " " + str(node.f) +" " +str(the_h)+" " + '\n')
if flag == 0:
flag = len(final_solution)
for i in range (1,flag):
node = final_solution[i]
f.write(str(node.e_point - node.parent.e_point) + str(node.cargo) + " " + str(node.f) +'\n')
f.close()
Program looks ok, check if the output is set ok, I set as a dummy filename, it worked, presuming code within the block after open has no compiler/interpreter error. The output file should be in the same directory where the source is.
output = "aa.txt"
with open(output, 'w') as f:
f.write("Negative numbers mean the empty space was moved to the left and positive numbers means it was moved to the right" + '\n')
if A == True:
the_h = node.h
elif A== False:
the_h = 0
f.write("Start " + str(node.cargo) + " " + str(node.f) +" " +str(the_h)+" " + '\n')
if flag == 0:
flag = len(final_solution)
for i in range (1,flag):
node = final_solution[i]
f.write(str(node.e_point - node.parent.e_point) + str(node.cargo) + " " + str(node.f) +'\n')
f.close()
You should not add f.close(), as the with statement will do it for you. Also ensure you don't reopen the file elsewhere with open(output, 'w') as that will erase the file.

Categories