Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/319.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
单独文件中的python日志信息_Python - Fatal编程技术网

单独文件中的python日志信息

单独文件中的python日志信息,python,Python,我正在用python创建一个程序,我需要记录通常会记录在数据库中的信息,但我现在无法实现。如何将数据写入包含dict矩阵的python文件 例如,如果main.py具有 name = raw_input("Please enter your name") age = raw_input("Please enter your age") hair_colour = raw_input("Pleas enter your hair colour") 我想将所有这些数据写入log.py文件,以便 l

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

例如,如果main.py具有

name = raw_input("Please enter your name")
age = raw_input("Please enter your age")
hair_colour = raw_input("Pleas enter your hair colour")
我想将所有这些数据写入log.py文件,以便

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

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

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循环为列表中的每个项目添加一行数据

也许像这样的事情可以达到目的:

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)))

它可以像一个JSON文件而不是log.py吗?这对你来说几乎是一样的,只是更便于携带(语言不可知)。你已经看过了吗?嗨,我得到一个错误
IndentationError:应该是缩进的块
@jack:唯一缩进的行是最后一行。试着取消它的记忆并重新记忆它。。。这可能与编辑器的配置有关…嗨,解决方案完全重写了文件。我需要它在}之前添加一行