Home > Blockchain >  How to remove a new line at the end of a file in python?
How to remove a new line at the end of a file in python?

Time:08-18

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?

CodePudding user response:

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)  # <-- you are writing the line that still have the new line character
                output.write(line.strip("\n"))  # try this?
os.replace('temp.txt', 'users.txt')  # Replace file with original name

Also as general tip I would recommend not using the term "input" as a variable name since it is reserved in python. Just letting you know as it can potentially cause some whacky errors that can be a pain to debug (speaking from personal experience here!)

================================================================

EDIT: I realize that doing this will likely not have any new line characters after you write the line, which will have all usernames on the same line. You will need to write a new line character after every name you write down except for the last one, which give you the trailing new line character that is causing you the problem.

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.
                output.write(line)
os.replace('temp.txt', 'users.txt')  # Replace file with original name

# https://stackoverflow.com/questions/18857352/remove-very-last-character-in-file
# remove last new line character from the file
with open("users.txt", 'rb ') as filehandle:
    filehandle.seek(-1, os.SEEK_END)
    filehandle.truncate()

This is admittedly a hackey way to go about it-- but it should work! This last section removes the last character of the file, which is a new line character.

CodePudding user response:

You don't need to use a temporary file for this.

def remove_user(filename, enteredUsername):
    last = None
    with open(filename, 'r ') as users:
        lines = users.readlines()
        users.seek(0)
        for line in lines:
            if not line.startswith(enteredUsername):
                users.write(line)
                last = line
        # ensure that the last line is newline terminated
        if last and last[-1] != '\n':
            users.write('\n')
        users.truncate()
  • Related