python - 如何在单独的文件中写入数组?
问题描述
我正在尝试将日期保存到单独文件(“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()
当脚本运行 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()
推荐阅读
- python-3.x - Pytorch:Backprop 中 grad_h_relu.clone() 的意义
- sql - 搜索重复项时如何加入表
- python-2.7 - 当percentile_approx基于groupby返回特定列的单个值时,如何选择另一列的对应值?
- c++ - Q_PROPERTY 可以泛化为多个基类吗?
- c# - 解析负数时出现FormatException
- php - PHP ODBC 查询不执行
- javascript - TypeError: combo.getSelection (...) 在渲染事件中为 null。外接程序 6
- typescript - Typescript 中的递归类型声明
- c++ - 由于常数为零,禁止比较总是错误的警告
- machine-learning - 使用 gensim 构建的 doc2vec 模型的 GridSearch