My issue is that when I type the new username to exchange to old username… the code works, but it adds the new username at the end of the text file, instead of exchanging the new username to the old username.
I tried with the due date and the task completed and I'm getting the same outcome.
Below you can see my code and where the issue is.
Thanks
https://cdn.discordapp.com/attachments/1065249947538169896/1065249947903078460/IMG_2651.jpg
https://cdn.discordapp.com/attachments/1065249947538169896/1065249948456718416/IMG_2654.jpg
My aim was to Exchange the username which is in index 0 to the new_name
CodePudding user response:
How to change username in file:
- Read lines
- Change the value of the username (by index)
- Clear file content
- Place the modified content For example:
file = open("your_filename.txt", 'r ')
index = 1
read = file.readlines()
read[index] = "new_name" '\n'
file.seek(0)
new_string = "".join(read)
print(new_string)
file.write(new_string)
CodePudding user response:
When you call file.write in append mode you just add the string to the end of the file, it doesn't know where you wanted it to be inserted.
if you want to work with regular files you have 2 options:
you can load the entire file content as a string, modify the relevant parts of that string and then dump the entire string into the file (in write mode), basically replacing the old file with a new one with the changed content.
you can use the fileinput module to make the changes in place.