【问题标题】:How Do I Write into an array on a seperate file?如何在单独的文件中写入数组?
【发布时间】:2019-10-10 17:49:34
【问题描述】:

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

【问题讨论】:

  • 你能说出你希望在文件中写什么吗?
  • 我正在尝试将三个值保存到文件上的数组中,然后能够调用它们
  • 有助于编写或标记语言。
  • 您没有阅读来自log.txt 的任何内容。您只是将从输入读取的值附加到log[]

标签: python arrays file


【解决方案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()

脚本运行 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()

【讨论】:

  • 谢谢 - 我如何从文件中检索这些并在 originia 程序上打印它们?
猜你喜欢
  • 2012-07-24
  • 1970-01-01
  • 2021-06-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多