Skip to main content
 首页 » 编程设计

python之在python中读取文件

2025年05月04日14birdshome

我需要读取如下文件:

config = { 
    'name': 'hello', 
    'see?': 'world' 
} 

使用像 name 和 see 这样的键? ,但我不想对脚本中的值进行硬编码。以及在这种情况下如何处理更深的嵌套。该文件可能包含更多这样的部分,我如何识别“名称”在运行时属于哪个部分。

请您参考如下方法:

如果您将结构编码为 JSON 数据,正如我认为您想要的那样,并且您在示例中所做的那样,您只需要在文件中写入和读取结构。 例如:

 import json  
 config = { 
  'name': 'hello', 
  'see?': 'world' 
 } 
 out = open('config.json','w') 
 out.write(json.dumps(config)) 
 out.close()  

配置文件已保存

 input = open('config.json','r') 
 config = json.loads(input.read()) 
 input.close() 
 print config 

重新加载配置文件