I'm creating a program to allow users to remove users which works, however, when it removes a user at the end of the file a new line character is not removed which breaks the program. The following is the a part of the function to remove the user.
with open("users.txt", "r") as input:
with open("temp.txt", "w") as output: # Iterate all lines from file
for line in input:
if not line.strip("\n").startswith(enteredUsername):
# If line doesn't start with the username entered, then write it in temp file.
output.write(line)
os.replace('temp.txt', 'users.txt') # Replace file with original name
This creates a temporary file where anything which doesn't start with a given string is written to the file. the name is then swapped back to "users.txt" I've looked on other threads on stackoverflow as well as other websites and nothing has worked, is there anything I should change about this solution?
EDIT --------------------
I managed to fix this with the following code (and thanks to everyone for your suggestions!):
count = 1 # Keeps count of the number of lines
removed = False # Initially nothing has been removed
with open(r"users.txt", 'r') as fp:
x = len(fp.readlines()) # Finds the number of lines in the file
if login(enteredUsername, enteredPassword) == True: # Checks if the username and password combinination is correct
with open("users.txt", "r") as my_input:
with open("temp.txt", "w") as output: # Iterate all lines from file
for line in my_input:
if not line.strip("\n").startswith(enteredUsername): # If line doesn't start with the username entered, then write it in temp file.
if count == x - 1 and removed == False: # If something has not been removed, get rid of newline character
output.write(line[:-1])
else:
output.write(line)
else:
removed = True # This only becomes true if the previous statement is false, if so, something has been 'removed'
count +=1 # Increments the count for every line
os.replace('temp.txt', 'users.txt') # Replace file with original name