【发布时间】: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\'))?