如何使我的代码无限制地执行输入和写入功能而无需复制粘贴它?
import time
now = time.strftime("%H:%M %d/%m/%Y:")
text = str(input("Nodus: "))
Nodus = open("Diário.txt","a")
Nodus.write(time.strftime("%H:%M %d/%m/%Y:"))
Nodus.write(' "%s"' % text)
Nodus.write("\n")
Nodus.close()
tet = open("Diário.txt","r")
tet2 = tet.read()
print (tet2)
time.sleep(5)
text = str(input("Nodus: "))
time.sleep(5)
text = str(input("Nodus: "))
time.sleep(5)
text = str(input("Nodus: "))
time.sleep(5)
答案 0 :(得分:0)
所以,你应该有一个while循环,你应该把写部分保留在一个函数中。
def write(input_):
Nodus = open("Diário.txt","a")
Nodus.write(time.strftime("%H:%M %d/%m/%Y:"))
Nodus.write(' "%s"' % input_)
Nodus.write("\n")
Nodus.close()
running = True
while running:
text = str(input("Nodus: "))
try:
write(text)
time.sleep(5)
except:
print('Error in command.')
所以这应该是完成的代码:
import time
now = time.strftime("%H:%M %d/%m/%Y:")
def write(input_):
Nodus = open("Diário.txt","a")
Nodus.write(time.strftime("%H:%M %d/%m/%Y:"))
Nodus.write(' "%s"' % input_)
Nodus.write("\n")
Nodus.close()
running = True
while running:
text = str(input("Nodus: "))
try:
write(text)
time.sleep(5)
except:
print('Error in command.')
tet = open("Diário.txt","r")
tet2 = tet.read()
print (tet2)