I am working on a project where i use a text file to store the data. I have a label for the user to enter the name and i want the user's name to be saved on line 41 of the file, which is the last line. I tried append but that just keeps adding a last line so if the user types another name it wont replace it but add another line. Can you please help me modify the code so it writes the name in line 41 of the text file and if there is already something on the text file, it just replaces line 41 based on the input. Until now i have this code but its not working i dont know why
def addUser(self):
global name
global splitname
name = self.inputBox.text()
splitname = name.split()
print("Splitname {}".format(splitname))
print(len(splitname))
self.usernameLbl.setText(name)
self.inputBox.clear()
# self.congratulations()
if name != "":
if len(splitname) == 2:
with open('UpdatedCourseInfo.txt', 'r', encoding='utf-8') as f:
data1 = f.readlines()
data1[40]= [f'\n{splitname[0]}, {splitname[1]}, 0, None, None']
with open('UpdatedCourseInfo.txt', 'w', encoding='utf-8') as f:
f.writelines()
f.close()
else:
with open('UpdatedCourseInfo.txt', 'r', encoding='utf-8') as f:
data1 = f.readlines()
data1[40]= [f'\n{splitname[0]}, 0, 0, None, None']
with open('UpdatedCourseInfo.txt', 'w', encoding='utf-8') as f:
f.writelines()
f.close()
print(name)
return name