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)
Related
I've tried to make a functioning sign up page, and whilst my input can be added to the file, I first want to make sure that the input of username does not already exist in the file. The function which checks this is as follows:
forename = forename_entry.get()
surname = surname_entry.get()
username = username_entry.get()
password = password_entry.get()
with open("data.txt", "r") as file:
end_of_file = False
while not end_of_file:
existent_username = file.readline().strip()
if existent_username == username:
additional_info_text.config(text="Username already exists, try choosing a different one",
font=("Ariel", 10))
submit_data.config(state="disabled")
end_of_file = True
else:
with open("data.txt", "a") as edit_file:
edit_file.write(forename + "\n")
edit_file.write(surname + "\n")
edit_file.write(username + "\n")
edit_file.write(password + "\n")
edit_file.write("" + "\n")
end_of_file = True
Keep in mind that submit_data.config(state="disabled") is there to check if my code was functioning in checking if it was there or not, but it did not. I don't understand where i am going wrong, but it is most likely in my first check. Any help is appreciated.
try if username in existent_username:
I am making some check-in system, just in case I want to build like a bot. But I am stuck building because my code returns syntax error. Can someone help me fix this?
I am making this code on Repl.it, one of the online IDE. I couldn't test it on eclipse because my python just isn't working.
import datetime
#This is where Name variable goes
#checkin = open(check-in.txt", "r")
i=0
while True:
it = input("Type in input: ")
if it == "Check-in list":
checkin = open("check-in.txt", "r")
if checkin.mode == "r":
contents = checkin.read()
print(contents)
checkin.close()
elif it == "Check-in":
checkin = open("check-in.txt", "a")
if checkin.mode == "a":
currentDT = datetime.datetime.now()
checkin.write((str(i+1) +". " + username + ":" + str(currentDT))
checkin.close()
Where error happens
checkin.close()
I have expect the output of "Type in input: " and when I type Check-in, the program should add number order, name, and time.
The output is: "SyntaxError: invalid syntax"
There are parentheses missing from checkin.write((str(i+1) +". " + username + ":" + str(currentDT)). Here is a fixed version: checkin.write((str(i+1) +". " + username + ":" + str(currentDT)))
Your parenthesis are not balanced. Add an extra ) after your checkin.write(... line.
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]))
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()
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())