单独fi中的python日志信息

2024-04-25 06:04:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用python创建一个程序,我需要记录通常会记录在数据库中的信息,但现在无法实现。如何将数据写入包含dict矩阵的python文件。你知道吗

例如,如果主.py有

name = raw_input("Please enter your name")
age = raw_input("Please enter your age")
hair_colour = raw_input("Pleas enter your hair colour")

我想把所有的数据都写到我的电脑上对数.py文件,以便

logs = {
    ...
    ...
    'the name': {'age':'the age', 'hair colour':'the hair colour'}
}

Tags: 文件the数据namepy程序inputage
2条回答

也许像这样的东西可以达到目的:

from pprint import pformat

log = dict()

name = raw_input("Please enter your name : ")
age = raw_input("Please enter your age : ")
hair = raw_input("Pleas enter your hair colour : ")

entry = dict()
entry['age'] = age
entry['hair'] = hair

log[name] = entry

with open('log.py', 'w') as logfile:
    logfile.write('log = {}'.format(pformat(log)))

这是一个非常老套的方法:

x = open('test.py','wb')
x.write('logs = { ')
x.write('"the name": {"test1": 1, "test2": 2, "test3": 3}')
x.write('}')
x.close()

In [27]: run test.py
In [28]: logs
Out[28]: {'the name': {'test1': 1, 'test2': 2, 'test3': 3}}

为了更好地使用,我只需要将您的用户输入与string.format合并在一起,用于您希望用作数据的部分。从所有输入的数据中创建一个列表,然后使用for循环为列表中的每个项目添加一行数据。你知道吗

相关问题 更多 >