【问题标题】:How to remove a new line at the end of a file in python?如何在python中删除文件末尾的新行?
【发布时间】:2022-08-17 22:32:06
【问题描述】:

我正在创建一个程序以允许用户删除有效的用户,但是,当它在文件末尾删除用户时,不会删除换行符,这会破坏程序。以下是删除用户的部分功能。

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

这将创建一个临时文件,其中不以给定字符串开头的任何内容都将写入该文件。然后将名称换回 \"users.txt\" 我已经查看了 stackoverflow 上的其他线程以及其他网站,但没有任何效果,我应该对此解决方案进行哪些更改?

  • 请注意,input 是内置的,因此您可能需要重命名它。为什么不直接做output.write(line.strip(\'\\n\'))

标签: python file text


【解决方案1】:
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

同样作为一般提示,我建议不要使用术语“输入”作为变量名,因为它是在 python 中保留的。只是让你知道,因为它可能会导致一些奇怪的错误,调试起来会很痛苦(从个人经验来看!)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-27
    • 1970-01-01
    • 1970-01-01
    • 2013-04-28
    • 2017-08-09
    • 1970-01-01
    相关资源
    最近更新 更多