首页 > 解决方案 > 如何在单独的文件中写入数组?

问题描述

我正在尝试将日期保存到单独文件(“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

标签: pythonarraysfile

解决方案


你可以用这个 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()

当脚本运行 2 次时,脚本的输出在文件中将如下所示foo.txt

[姓名, 888888, 01]

[姓名2, 998878, 02]

将 foo.txt 文件打印到屏幕的代码。

file_handler = open('footxt.txt')

for line in file_handler.readlines():
    print (line)

file_handle.close()

推荐阅读