如何排除用户输入的最后一行



我正在尝试获取用户输入,以便在运行时编写文件。但是它也写入分隔符(-99(。有没有比这更简单的代码不包括分隔符?

过去,我曾在Jupyter实验室试用过Python 3。

lines=input("Enter the contents:")
while(lines!="-99"):
lines=input()
file.write(lines)
file.write("n")
file.close()

我期望用户内容的输出达到-99(即,不包括-99(,但实际输出是-99的用户内容。

样本输出

Enter the contents:
Hi
Hello
Welcome to python lab
-99

在我的输出文件中:

Hi
Hello
Welcome to python lab
-99

只需重写while循环,即可在写入文件之前中断。

print("Enter the contents:")
with open(file_name, "w") as file:
while True:
line = input()
if line == "-99":
break
print(line, file=file)

我对代码做了一些其他改进。

简化循环

您可以使用fileinput:

for line in fileinput.input():
if line == "-99":
break
print(line, file=file)

在Python 3.8中,您将能够使用walrus运算符:

while (line := input()) != "-99":
print(line, file=file)

试试这个,

print("Enter the contents: ")
with open(file_name, "a") as file:
while True:
data = input()
if data == '-99':
break
else:
file.write(data+'n')

这样一来,-99就不会存储在您的文件中。

这里有一个不写-99但终止于它的解决方案:

filename= 'test.out' 
def contents(): 
return input ("Enter the Contents: ") 
getcontents=contents() 
with open (filename, 'w') as f: 
while getcontents != '-99': 
f.write(getcontents + "n") 
getcontents=contents() 

最新更新