My code is trying to delete the oldest score in a text file when the number of scores is bigger than three. This is the text file:
humzah:0:6:5
ikrah:8:6:4
This is my code:
if userclass=="1": #if userclass is equal to 1
with open ("Class1scores.txt", "r") as dataforclass1:#open the class 1 file as
#data for class 1 in read plus mode
lines = dataforclass1.read().splitlines() #lines is equal to each line on
#the file (list).
for lineno1, line in enumerate(lines): #for the line number
usertaken=input("Have you taken this quiz before, yes or no") #first ask if the user
#has done this quiz before
while True: #this states that while it is true
if usertaken=="yes": #if the user says yes continue the script
break
if usertaken=="no": #if the user says no continue the script
break
else:
print("That is not a valid answer! yes or no")#if the user
continue
if usertaken=="yes": #if they have then find the line and add to it
if line.startswith(username):
print("was found on line", lineno1) #tells the user what lines their name is on
lines[lineno1] += ":" + str(score)
break
else:
lines.append(username + ":" + str(score)) #if they have not add to
#a new line
break
data = "\n".join(lines) + "\n" #data is the list plus indents (\n means new
#line)
with open("Class1scores.txt", "w") as file: #opens the file in write mode
file.write(data) #this writes in to the file
print(data)
with open('Class1scores.txt','r') as class1file:#with the text file
#as class1file
lines = []#this creates an empty list
for x, line in enumerate(class1file):#to find x read the lines
if lineno1==x:
class1_list = line.split(':')#split the text file by :
if len(class1_list) > 4:#if theres more than 4 values
del class1_list[1]#delete the first score
line = ':'.join(class1_list)#the line is equal to the
#data with : as the seperator
lines.append(line)#append this to the list
with open("Class1scores.txt",'w') as writefile:
writefile.write(''.join(lines))
For class 1 it just loops the question "have you taken this quiz before" and for the other classes , with the same code copied and pasted, it states "lineno1 is not defined". Any help?
lineno1 is only defined in the if-block where userclass equals 1. In all other cases the variable is never defined and therefore the error is thrown.
If you define lineno1 in the first line of your code, it will be overwritten in the first if-block but you can also use in the 2nd if-block.
Related
everyone. I have a Python assignment that requires me to do the following:
Download this CSV fileLinks to an external site of female Oscar winners (https://docs.google.com/document/d/1Bq2T4m7FhWVXEJlD_UGti0zrIaoRCxDfRBVPOZq89bI/edit?usp=sharing) and open it into a text editor on your computer
Add a text file to your sandbox project named OscarWinnersFemales.txt
Copy and paste several lines from the original file into your sandbox file. Make sure that you include the header.
Write a Python program that does the following:
Open the file and store the file object in a variable
Read the entire contents line by line into a list and strip away the newline character at the end of each line
Using list slicing, print lines 4 through 7 of your file
Write code that will ask the user for an actress name and then search the list to see if it is in there. If it is it will display the record and if it is not it will display Sorry not found.
Close the file
Below is the code I currently have. I've already completed the first three bullet points but I can't figure out how to implement a search function into the list. Could anyone help clarify it for me? Thanks.
f = open('OscarsWinnersFemales.txt')
f = ([x.strip("\n") for x in f.readlines()])
print(f[3:7])
Here's what I tried already but it just keeps returning failure:
def search_func():
actress = input("Enter an actress name: ")
for x in f:
if actress in f:
print("success")
else:
print("failure")
search_func()
I hate it when people use complicated commands like ([x.strip("\n") for x in f.readlines()]) so ill just use multiple lines but you can do what you like.
f = open("OscarWinnersFemales.txt")
f = f.readlines()
f.close()
data = {} # will list the actors and the data as their values
for i, d in enumerate(data):
f[i] = d.strip("\n")
try:
index, year, age, name, movie = d.split(",")
except ValueError:
index, year, age, name, movie, movie2 = d.split(",")
movie += " and " + movie2
data[name] = f"{index}-> {year}-{age} | {movie}"
print(f[3:7])
def search_actr(name):
if name in data: print(data[name])
else: print("Actress does not exist in database. Remember to use captols and their full name")
I apologize if there are any errors, I decided not to download the file but everything I wrote is based off my knowledge and testing.
I have figured it out
file = open("OscarWinnersFemales.txt","r")
OscarWinnersFemales_List = []
for line in file:
stripped_line = line.strip()
OscarWinnersFemales_List.append(stripped_line)
file.close()
print(OscarWinnersFemales_List[3:7])
print()
actress_line = 0
name = input("Enter An Actress's Name: ")
for line in OscarWinnersFemales_List:
if name in line:
actress_line = line
break
if actress_line == 0:
print("Sorry, not found.")
else:
print()
print(actress_line)
so I'm currently trying to print a list of cards in a text based card battler I'm making for a school project, and I'm wondering if I can get some help. I'm trying to print something different if a line in a file is 0 or 1, but I can't figure it out. thanks if you can help
def mainfunc():
while i<cardlist:
#if it's zero, do this
print("the card this line represents")
#if it's one, do this
print("locked")
#else, becasue if it's else then you're at the end of the file
print("your deck:")
#print your current deck
print("which card do you want to add?")
print(filelinecount("RIPScards"))
This is what I would do (UPDATED):
# For preventing unwanted behavior if this file ever gets imported in another:
if __name__ == "__main__":
with open(**insert file path here**, 'r') as f:
for line in f:
if line.strip() == "0":
print("the card this line represents")
elif line.strip() == "1":
print("locked")
else:
print("your deck")
print("which card do you want to add?")
print(filelinecount("RIPScards"))
You can read a file line-by-line with it open like so:
with open(**file path**, 'r') as f:
for line in f:
# Do stuff with the line here
Or you can read all the lines one time and close the file, then do stuff with the lines, like so:
f = open(**file name here**, 'r')
$lines = f.readlines()
f.close() # Make sure to close it, 'with open' method automatically does that for you, but manually opening it (like in this example) will not do it for you!
# Do stuff with it:
for line in lines:
# Do something with the line
Hopefully that helps!
I'm trying to replace a specific part of a line in a txt file, but it says "AttributeError: 'list' object has no attribute 'replace'".
This is part of my code:
with open("credentials.txt",'r+') as f:
credentials_array = f.readlines() # credentials_array contains the txt file's contents, arranged line by line. so credentials_array[0] would be the first login info in the file
lines_in_credentials = len(credentials_array) # if there are 7 credentials in the text file, lines_in_credentials = 7.
while x < lines_in_credentials:
if user in credentials_array[x]: # go through each line in turn to see if the login_username is in one. line 1, credentials_array[1].
credentials_desired_line = credentials_array[x]
username_password_score = credentials_array[x].split(",") # username_password_score is the contents of each line, the contents are split by commas
stored_username = username_password_score[0] # username is part 1
stored_password = username_password_score[1] # password is part 2
stored_score = username_password_score[2] # score is part 3
stored_score_int = int(stored_score)
if user == stored_username:
if new_score > stored_score_int:
print("Congratulations! New high score!")
print(stored_score_int,"-->",new_score)
credentials_array_updated = stored_username+","+stored_password+","+str(new_score) # reassign the array[x] to having new_score at the end instead of stored_score
credentials_array.replace(credentials_array[x],credentials_array_updated)
break
Is there any other way to do it?
Your missing a line setting x = 0 in your presented problem, but that's not important - I think that's just a typo you've missed when writing it out.
Your line:
credentials_array.replace(credentials_array[x], credentials_array_updated)
is your problem. Try:
credentials_array[x].replace(credentials_array[x], credentials_array_updated)
replace operates on the string, and you want to replace the string within credentials_array[x], not the whole list.
Now, I have assumed there are more entries to credentials_desired_line than what you've outlined in username_password_score. Otherwise you could do just a straight replacement such as:
credentials_array[x] = credentials_array_updated
As a bigger change, you could try this:
iLines = 0
with open("credentials.txt",'r+') as f:
credentials_array = f.readlines()
for line in credentials_array:
if user in line: #user we want is in this line
currScore = int(credentials_array[x].split(",")[2])
if new_score > currScore:
print("Congratulations! New high score!")
print(Str(currScore),"-->",str(new_score))
credentials_array[iLines].replace(str(currScore),str(newScore))
break
iLines =+1
With you wanting to update the text file, the minimal mod to your code would be to put this at the end (beyond/outside) the previous "with open()" loop:
with open('credentials.txt', 'w') as f:
for line in credentials_array:
f.write("%s\n" % line)
elif menuOption == "2":
with open("Hotel.txt", "a+") as file:
print (file.read())
Ive tried many different ways but my python file just refuses to print the txt contents. It is writing to the file but option 2 wont read it.
if menuOption == "1":
print("Please Type Your Guests Name.")
data1 = (input() + "\n")
for i in range (2,1000):
file = open("hotel.txt", "a")
file.write(data1)
print("Please Write your Guests Room")
data2 = (input("\n") + "\n")
file.write(data2)
data3 = random.randint(1, 999999)
file.write(str (data3))
print("Guest Added - Enjoy Your Stay.")
print("Guest Name is:", data1)
print("Guest Room Number Is:", data2)
print("Your Key Code Is:", data3)
I want all the above information to be added to a TXT. (That works) and then be able to read it also. which won't work.
Why and how can I fix?
You have to use r instead of a+ to read from file:
with open("Hotel.txt", "r") as file:
You are using a+ mode which is meant for appending to the file, you need to use r for reading.
Secondly I notice this
for i in range (2,1000):
file = open("hotel.txt", "a")
You are opening a new file handler for every iteration of the loop. Please open the file just once and then do whatever operations you need to like below.
with open("hotel.txt", "a") as fh:
do your processing here...
This has the added advantage automatically closing the file handler for you, otherwise you need to close the file handler yourself by using fh.close() which you are not doing in your code.
Also a slight variation to how you are using input, you don't need to print the message explicitly, you can do this with input like this.
name = input("Enter your name: ")
I'm making a program that stores data in a text file, I can search for data line by line, and I made a (delete function) that is quoted below, making a variable 'a' adding to it the (non deleted lines), and ask before deletion for results and if not confirmed it would be added also to 'a', then rewrite the (file) with'a' omitting the deleted lines.
THE PROBLEM IS:
all results are deleted not only the confirmed one desbite that:
#deleting line
confirm = input('confirm to delete [y]/[n]>>')
if confirm != 'y':
a += line
so, why did this problem happen and how to fix it?
Next is the whole code of delete function:
searching = input('enter any information about query: ')
searching = searching.lower() # converting words in lower case
f = open(file, 'r')
lines = f.readlines()
f.close()
print('Word | Definition | Remarks')
a = '' # we will store our new edited text here
for line in lines:
line_lower_case = line.lower() # changing line in lower case temporary
# because contact != COntact and will not appear in searcch
if searching in line_lower_case:
print('Query found')
print()
print('>>',line, end = '') # printing words in the same case as been added
# end = '', to prevent printing new line avoiding extra empty line
#deleting line
confirm = input('confirm to delete [y]/[n]>>')
if confirm != 'y':
a += line
#elif confirm =='y':
# pass # it will just do nothing, and will not add line to 'a'
continue # to search for more queries with the same searching entry
print()
a += line #we add each line to the 'a' variable
f = open(file,'w')
f.write(a) #we save our new edited text to the file
f.close()
I changed the indentations of the program and that was the issue as I agreed with #TheLazyScripter and that should work now if I understood your problem correctly, I did a bunch of tests and they did work. I noticed that you didn't define what input file will be and I add that line of code at line 3 which will through an error if the file not defined.
searching = input('enter any information about query: ')
searching = searching.lower() # converting words in lower case
file = "test.txt" #your file
f = open(file, 'r')
lines = f.readlines()
f.close()
print('Word | Definition | Remarks')
a = '' # we will store our new edited text here
for line in lines:
line_lower_case = line.lower() # changing line in lower case temporary
# because contact != COntact and will not appear in searcch
if searching in line_lower_case:
print('Query found')
print()
print('>>',line, end = '') # printing words in the same case as been added
# end = '', to prevent printing new line avoiding extra empty line
#deleting line
confirm = input('confirm to delete [y]/[n]>>')
if confirm != 'y':
a += line
#elif confirm =='y':
# pass # it will just do nothing, and will not add line to 'a'
continue # to search for more queries with the same searching entry
print()
a += line #we add each line to the 'a' variable
f = open(file,'w')
f.write(a) #we save our new edited text to the file
f.close()