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]))
Related
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.
Writing a game and no matter what I try it keeps giving me a syntax error for the 'as'.
I have tried looking through StackOverflow / changing my code to find a workaround but I have been unable to fix it so far
winner = input("Winner test username")
winnerscore = input("Test score")
open("leaderboardtest.txt","a") as leaderboard
leaderboard.write = "/n" , winner , " : " , winnerscore
(winner and winnerscore variables would have been made earlier just wrote it here during testing)
Invalid syntax highlight on the 'as'.
(I know this is a comparatively simple problem to other things on StackOverflow but I would appreciate any support.)
Looks like you have used incorrect syntax for writing text into file.
f = open("leaderboardtest.txt","a") # open file for append operation
f.write('\n' + winner + ' : ' + winnerscore) # write data whatever you want
f.close() # close file
There you go.
winner = input("Winner test username")
winnerscore = input("Test score")
with open("leaderboardtest.txt","a") as leaderboard:
string_to_write = "\n" + winner + " : " + winnerscore
leaderboard.write(string_to_write)
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()
Using windows 10
Here's a sample of my code, where the problem is:
if choice2 == "d":
amount = int(raw_input("How much money would you like to deposit? Current balance: %i : " % intBalance))
newBalance = intBalance + amount
print "Current balance: %i" %newBalance
f.close()
os.remove("accounts.txt")
f = open("accounts.txt", "a+")
fileVar.remove(accessedAccount[2])
fileVar.remove(accessedAccount[1])
fileVar.remove(accessedAccount[0])
f.write(accessedAccount[0] + "\n")
f.write(accessedAccount[1] + "\n")
newBalance = str(newBalance)
f.write(newBalance + "\n")
for item in fileVar:
f.write("%s\n" %item)
test = raw_input("Waiting for input")
At the bottom is the code that writes the information of the list (called fileVar) into the text file (called f). It does write the information to the list but it messes up the order of the lines which cannot happen with the program I am making because the file must be able to be read back to the program to work later on.
Here is my entire code for context:
import os
import string
again = "y"
f = open('accounts.txt', 'a+')
fileVar = f.read().splitlines()
print fileVar
accessedAccount = []
data = f.read()
choice = raw_input("What would you like to do? (add/remove a bank account, access a bank account): ")
if choice == "a":
while again == "y":
accName = raw_input("Account owner's name: ")
accType = raw_input("Account type: ")
accBal = "0"
f.seek(0, 2)
f.write(accName + "\n")
f.write(accType + "\n")
f.write(accBal)
f.write("\n")
again = raw_input("Add another account?: ")
if choice == "a2":
account = raw_input("What is the name of the account you wish to access?: ")
for i, line in enumerate(fileVar):
if account in line:
for j in fileVar[i:i+3]:
print j
accessedAccount.append(j)
print accessedAccount
balance = accessedAccount[2]
intBalance = int(balance)
print accessedAccount
choice2 = raw_input("This is your bank account. What would you like to do now? (Withdraw/deposit, exit): ")
if choice2 == "d":
amount = int(raw_input("How much money would you like to deposit? Current balance: %i : " %intBalance))
newBalance = intBalance + amount
print "Current balance: %i" %newBalance
f.close()
os.remove("accounts.txt")
f = open ("accounts.txt", "a+")
fileVar.remove(accessedAccount[2])
fileVar.remove(accessedAccount[1])
fileVar.remove(accessedAccount[0])
f.write(accessedAccount[0] + "\n")
f.write(accessedAccount[1] + "\n")
newBalance = str(newBalance)
f.write(newBalance + "\n")
for item in fileVar:
f.write("%s\n" %item)
test = raw_input("Waiting for input")
if choice2 == "w":
amount = int(raw_input("How much money would you like to withdraw? Current balanace: %i : " %intBalance))
newBalance = intBalance - amount
print "Current Balance: %i" %newBalance
f.close()
os.remove("accounts.txt")
f = open ("accounts.txt", "a+")
fileVar.remove(accessedAccount[0])
fileVar.remove(accessedAccount[1])
fileVar.remove(accessedAccount[2])
f.write(accessedAccount[0] + "\n")
f.write(accessedAccount[1] + "\n")
newBalance = str(newBalance)
f.write(newBalance + "\n")
for item in fileVar:
f.write("%s\n" %item)
test = raw_input("Waiting for input")
if choice == "r":
removeChoice = raw_input("What is the name of the account you wish to remove?: ")
f.close()
os.remove("accounts.txt")
f= open("accounts.txt", "a+")
for i, line in enumerate(fileVar):
if removeChoice in line:
for j in fileVar[i:i+3]:
accessedAccount.append(j)
fileVar.remove(accessedAccount[0])
fileVar.remove(accessedAccount[1])
fileVar.remove(accessedAccount[2])
for item in fileVar:
f.write("%s\n" %item)
f.close()
for example, the original text file looks like this:
Ryan
Savings
0
John
Chequings
0
Carly
Savings
0
when it is re-written with edited information, what it is supposed to look like, if 300 dollars were added to Carly's account:
Carly
Savings
300
Ryan
Savings
0
John
Chequings
0
What it looks like instead:
Carly
Savings
300
John
Chequings
Ryan
0
Savings
0
Thank you in advance :)
Not a direct answer to your question, but some pointers which may end up making it much easier for both yourself and others to debug your code.
1) Functions are your friend. See if you can take small tasks and break them up into functions. For example, writing out someone's balance to a file could be a small function, which you might call like:
def write_balance_to_file(account_details):
...function code goes here...
account_details = {name:"Ryan", account:"Savings", balance:1000}
write_balance_to_file(account_details)
Opening and closing the file should be handled within that function, and preferably using:
with open('filename', 'a+') as f:
f.write("A thing to write")
Note that you don't need to close the file manually when doing this.
2) Use a dictionary for storing a person's account details, rather than a list. Multiple accounts can be stored as a list of dictionaries. This makes it a lot easier to read as call such as:
f.write(accessedAccount[0] + "\n")
which becomes:
f.write(accessedAccount['name'] + '\n')
You can then pass in this dictionary to the write_balance_to_file method you will create. :)
3) Consider a tab-separated format for your accounts.txt file. Remember to escape/remove any tabs in your user input. This way each account will be on one line.
4) Possibly a little way in the future for you, but be aware that unit-testing exists, and is good practice. In essence, you can write tests (usually using a test framework such as py.test) which test each function/class/module under different input conditions. Anything that you can't break up into small, testable code fragments (functions or classes) is probably not good code. Writing tests is a great way to identify bugs in your code, and often helps to clarify your thinking. ALWAYS TEST!
For a minimal change that will solve the issue, this is the code that needs to change:
for i, line in enumerate(fileVar):
if account in line:
for j in fileVar[i:i+3]:
print j
accessedAccount.append(j)
This records which entries are part of the accessedAccount however later on you just remove the first occurence of these entries:
fileVar.remove(accessedAccount[2])
fileVar.remove(accessedAccount[1])
fileVar.remove(accessedAccount[0])
but if the entry is something as simple as 0 then it will not necessarily remove it from the correct place, so instead pop the accessed account out of the fileVar when putting them into accessedAccount:
for i, line in enumerate(fileVar):
if account in line:
for j in range(3):
print i+j
accessedAccount.append(fileVar.pop(i+j))
#break # you probably want to stop checking by this point
This will remove the relevent lines from fileVar and put them in accessedAccount so the order of lines will not be messed up by using .remove, and then obviously comment out the calls to .remove:
## fileVar.remove(accessedAccount[2])
## fileVar.remove(accessedAccount[1])
## fileVar.remove(accessedAccount[0])
This should fix the immediate problem of taking out the wrong lines.
This is my code to opening the file; I would like it to contain a name and a figure:
file_n = "Class_" + str(num_class) + ".txt"
file = open(file_n,"r")
string = file.read()
file.close()
and this is the error message I keep getting and I can't work out how to fix it:
file = open(file_n,"r")
IOError: [Errno 2] No such file or directory: 'Class_2.txt'
Could someone please tell me why this happening and the solution to it?
im still very confused
this is my whole code:
import random
import json
score = 0
turn = 1
turn = turn + 1
name = raw_input("what is your name?")
num_class = input("What class are you in? (1,2,3)")
print ("hello "+name+" have fun and good luck!")
for turn in range(10):
randnum_1 = random.randint(1,10)
randnum_2 = random.randint(1,10)
operators = ["+", "-", "*"]
operator_picked = operators[random.randint(0,2)]
human_answer = raw_input("What is " + str(randnum_1) +" "+ operator_picked +" " + str(randnum_2) + "?")
correct_answer = str((eval(str(randnum_1) + operator_picked + str(randnum_2))))
if correct_answer == human_answer :
score = score+1
print ("Correct!")
else:
print ("Incorrect!" +"The correct answer is " + str(correct_answer))
print("\nYour score was " + str(score)+ "/10")
file_name = ("Class_" + str(num_class) + ".txt")
file = open(file_n,"r")
string = file.read()
file.close()
dict = {}
Like Kevin and Flavian mentioned the directory of Class_2.txt is most likely not the directory where your script is located.
file_n = "/ActualDirectory/ofFile/Class_" + str(num_class) + ".txt"
Make sure that your Python code lies in the same directory with your txt file.
So it should be like this:
Of course the two files can be in different directories, but then you should provide the relevant, or absolute, path of the txt file to your code.
As 1001010 stated, you could check your current directory by doing:
import os
print(os.getcwd())