简体   繁体   English

如何将字典存储在文件中(Python)

[英]How to store a dictionary in a file (Python)

I am new to python and I wanted to know if there is any way that I can store a dictionary in a file without using any module?我是 python 的新手,我想知道是否有任何方法可以在不使用任何模块的情况下将字典存储在文件中? Example of Dictionary -字典示例 -

credentials = {
  "username" : "ABC",
  "email"    : "abc@email.com",
  "password" : "abc123@#"
}

Sure you can, the simplest way is just calling str() on it:当然可以,最简单的方法就是调用str()

with open("out.txt", "w") as file:
    file.write(str(<dict>))

Though it's probably not the smartest way to do it since you'll need to retrieve it back and then the problem might occur.尽管这可能不是最明智的方法,因为您需要将其取回,然后可能会出现问题。

Instead perhaps use json.dumps() (or json.dump() if you prefer using file descriptor), or serialize it to XML (manually since there's no simple "dumps()" as for json) or pickle.dumps() .相反,也许使用json.dumps() (或json.dump()如果您更喜欢使用文件描述符),或将其序列化为 XML (手动,因为对于 json 没有简单的“ pickle.dumps() ”)或pickle.dumps()

To retrieve the value back then use:要检索该值,然后使用:

import os

credentials = {
  "username" : "ABC",
  "email"    : "abc@email.com",
  "password" : "abc123@#"
}

for c in credentials:
    file_data = credentials.items()
file_name = os.path.join(os.path.dirname(__file__), 'test.txt')

with open(f'{file_name}.txt', 'w') as write_file:
    write_file.write(str(file_data))

you need to use json format你需要使用json格式

import json
credentials = {
  "username" : "ABC",
  "email"    : "abc@email.com",
  "password" : "abc123@#"
}

with open("creds.json", "w") as outfile: 
    json.dump(credentials, outfile)


without Any module没有任何模块

credentials = {
  "username" : "ABC",
  "email"    : "abc@email.com",
  "password" : "abc123@#"
}

with open("creds.txt", "w") as outfile:
    outfile.write(str(credentials))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM