gpt4 book ai didi

python - 如何写入单独文件上的数组?

转载 作者:行者123 更新时间:2023-12-01 07:08:45 24 4
gpt4 key购买 nike

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

最佳答案

您可以使用此 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 文件中。

[name, 888888, 01]

[name2, 998878, 02]

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

file_handler = open('footxt.txt')

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

file_handle.close()

关于python - 如何写入单独文件上的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58328515/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com