简体   繁体   English

如何删除 python 中文件末尾的新行?

[英]How to remove a new line at the end of a file in python?

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.下面是function去掉用户的部分。

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?然后将名称交换回“users.txt”我查看了stackoverflow以及其他网站上的其他线程并且没有任何效果,我应该对此解决方案进行任何更改吗?

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
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.同样作为一般提示,我建议不要使用术语“输入”作为变量名,因为它在 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.诚然,这对于 go 来说是一种骇人听闻的方式——但它应该可以工作,最后一部分删除了文件的最后一个字符。 which is a new line character.这是一个换行符。

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 python - 如何从行之间删除换行符而不从行尾删除换行符? - How to remove new-line characters from in between a line without removing the new-line from end of the line python? Python在打开的文件末尾添加了新行 - Python adds a new line at the end of opened file Python 中是否有任何快捷方式可以删除文件中每行末尾的所有空格? - Is there any shortcut in Python to remove all blanks at the end of each line in a file? 从python中的文件中删除每行开头和结尾的空格 - Remove whitespaces from beginning and end of each line in a file in python 如何使用Python删除文本文件中一行中间的随机新行? - How do I remove a random new line in the middle of a line in a text file using Python? Python输出:如何删除新行的缩进? - Python output: how to remove indent of a new line? 如何在python中找到文件结尾的行号? - How to find the line number of the end of file in python? 在 Python 中的文件末尾添加文本,但不创建新行 - Add text to the end of a file in Python, but without creating a new line 如何从 python 中特定行的字符串开头和结尾删除引号? - How to remove quotes from start and end of the string at a specific line in python? 如何在python3的每一行末尾删除此多余的尾随空格 - How to remove this extra trailing space at the end of each line in python3
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM