我正在尝试将日期保存到单独文件(“ file.txt”)中的数组(log [])中。 我该怎么办?
我已经打开了文件本身,但是我不知道如何在该文件中打开log []并将数据附加到文件中。
x = input("Please Enter Name: ")
y = input("Please Enter Phone Number: ")
z = input("Please Enter Room Number: ")
with open("log.txt", "a") as f:
with open("log[]", "a") as g:
g.write("Name: " + x)
g.write("Phone Number: " + y)
g.write("Room Number: " + z)
when doing this, it opened up a new file called log[] and saved it into there, not the actual array in log.txt. Then log.txt displayed that the login crashed
答案 0 :(得分:1)
您可以使用此python脚本解决问题。
x = input("Please Enter Name: ")
y = input("Please Enter Phone Number: ")
z = input("Please Enter Room Number: ")
# {} are the place holder of x, y and z
# \n means new line at the end of each write done in the file.
log = '[{}, {}, {}]\n'.format(x, y, z)
# footxt in the same dir as the python script.
file_handler = open('footxt.txt', 'a')
file_handler.writelines(log)
file_handler.close()
脚本运行两次后,其输出将在foo.txt
文件中显示。
[姓名,888888,01]
[name2,998878,02]
将foo.txt文件打印到屏幕的代码。
file_handler = open('footxt.txt')
for line in file_handler.readlines():
print (line)
file_handle.close()