Reputation: 1
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?
Upvotes: 0
Views: 1350
Reputation: 1275
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)
Upvotes: 1