如何让python解释器请求输入和写入文件

时间:2018-03-29 01:58:08

标签: python-3.x

如何使我的代码无限制地执行输入和写入功能而无需复制粘贴它?

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)

1 个答案:

答案 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)
相关问题