"AttributeError: 'list' object has no attribute 'replace' - python

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)

Related

Creating a search function in a list from a text file

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)

Trouble with matching variables to line in txt, and removing line

I am having trouble with matching variables to lines in txt, and removing the lines.
I am currently doing a hotel room booking program in which I am having trouble removing a booking from my text file.
This is how my lines in my text file are formatted:
first_name1, phonenumber1 and email 1 are linked to entry boxes
jeff;jeff#gmail.com;123123123;2019-06-09;2019-06-10;Single Room
def edit_details(self,controller):
f = open("Bookings.txt")
lines = f.readlines()
f.close()
x = -1
for i in lines:
x += 1
data = lines[x]
first_name1 = str(controller.editName.get())
phonenumber1 = str(controller.editPhone.get())
email1 = str(controller.editEmail.get())
checkfirst_name, checkemail, checkphone_num, checkclock_in_date, checkclock_out_date, checkroom = map(str, data.split(";"))
if checkfirst_name.upper() == first_name1.upper() and checkemail.upper() == email1.upper() and checkphone_num == phonenumber1:
controller.roomName.set(checkfirst_name)
controller.roomEmail.set(checkemail)
controller.roomPhone.set(checkphone_num)
controller.roomCheckin.set(checkclock_in_date)
controller.roomCheckout.set(checkclock_out_date)
controller.roomSelect.set(checkroom)
print(controller.roomName.get())
print(controller.roomSelect.get())
controller.show_frame("cancelBooking")
break
elif x > len(lines) - int(2):
messagebox.showerror("Error", "Please Enter Valid Details")
break
I have the user to enter their details to give me the variables but I don't know how to match these variables to the line in the text file to remove the booking.
Do I have to format these variables to match the line?
This is what i have tried but it deletes the last line in my file
line_to_match = ';'.join([controller.roomName.get(),controller.roomEmail.get(),controller.roomPhone.get()])
print(line_to_match)
with open("Bookings.txt", "r+") as f:
line = f.readlines()
f.seek(0)
for i in line:
if i.startswith(line_to_match):
f.write(i)
f.truncate()
I have kind of added a pseudocode here. You can join the variables using ; and validate if the line startswith those details, like below.
first_name1, phonenumber1, email1 = 'jeff', 'jeff#gmail.com', '123123123'
line_to_match = ';'.join([first_name1, email1, phonenumber1])
for i in line:
...
if i.startswith(line_to_match):
# Add your removal code here
...

Why doesn't my defined delete function working proberly in python? all results are deleted

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()

Why does this coden tell me lineno1 doesnt exist?

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.

Want to overwrite specific character on a specific line in a text file with new characters in Python

I Have a program that calculates a score 'LevelScore' and i want to open the UserFile 'UserScoreFile' and check against the current user score saved in the file, and if LevelScore > CurrentScore overwrite the previous characters representing that levels score in the text file to the LevelScore.
Each line in the Text file represents a level from 0-7 with each line format being, "T 000", T is representing if level is unlocked and 000 represents the current score (score can be 0-100) "lev" is a variable from 0-7 indicating which level the user is on.
UserFileR = open("UserScoreFile.txt","r")
UserFileLines = UserFileR.readlines()
UserLevelLine = UserFileLines[lev]
UserLevelScore = UserLevelLine[2:5]
if LevelScore > UserLevelScore:
UserFileWR = open("UserScoreFile.txt","r+")
#This is where i dont know what to do...
This should get you started.
UserFileRW = open("UserScoreFile.txt","r+")
UserFileLines = UserFileR.readlines()
UserLevelLine = UserFileLines[lev]
UserLevelScore = int(UserLevelLine[2:5])
if int(LevelScore) > UserLevelScore:
UserFileRW.truncate()
UserFileLines[lev] = "some tex" + str(LevelScore) # there is something before score, but I don't know what
UserFileRW.write(''.join(UserFileLines))
UserFileRW.close()
Unfortunately this is not possible to change something in the middle of file. So you have to parse all of it, make modifications and then write it again.
Here's the solution me and Luke have come up with collaboratively:
UserFileRW = open("UserScoreFile.txt","r+")
UserFileLines = UserFileRW.readlines()
UserLevelLine = UserFileLines[lev]
UserLevelScore = int(UserLevelLine[2:])
UserFileRW.close()
if LevelScore > UserLevelScore:
UserFileWR = open("UserScoreFile.txt","w+")
UserFileLines[lev] = "T " + str(LevelScore) + "\n"
UserFileRW.writelines(UserFileLines)
UserFileRW.close()
Thank you to Jotto and Tim Pietzcker for your contributions.
Using the fileinput module, you could do this:
import fileinput
with fileinput.input(files=["test.txt"], inplace=True) as f:
for line in f:
if fileinput.lineno() == lev+1: # line numbers start at 1, not 0
UserLevelScore = int(line[2:5]) # assuming LevelScore is an int
if LevelScore > UserLevelScore:
line = "{}{:0>3}".format(line[:2], LevelScore)
# right-justify LevelScore with leading zeroes
print(line, end="") # Output is redirected to the current line of the file

Categories

Resources