2016-01-04 130 views
2

我的代碼涉及以字典的形式導入和導出用戶名和密碼。爲了導出字典,我將其更改爲一個字符串。 這是導入的文本文件(這是在代碼中的出口相同的格式):字符串到字典轉換

{'account1': 'password'}{'account2': 'password'} 

代碼出口如下:

accounts=open("accounts.txt","r") 
accounts=accounts.read() 

newaccount={username:password}#user name and password are user defined 
str1=str(newaccount) 
updated=open("accounts.txt","w") 
updated.write(accounts) 
updated.write(str1) 
updated.close() 

我想字典的樣子這樣的:

{'account1':'password', 'account2':'password'} 
+0

爲什麼不以較容易解析的格式導出字典? – erip

+3

不要重新發明輪子,除非是爲了訓練目的。使用[json.dump](https://docs.python.org/3/library/json.html#basic-usage)在文件中轉儲字典並使用[json.load]加載它(https:// docs .python.org/3/library/json.html#json.load) – Pynchia

+0

我建議你使用'json'對象來保存你的字典,因爲這樣你就不能很容易地從你的文件中讀回它 –

回答

-1

你可以使用Python泡菜模塊:

import pickle 
accounts = {'account1': 'password'}{'account2': 'password'} 
pickle.dump(accounts, open("save.p", "wb")) 

要加載字典,

accounts = pickle.load(open("save.p", "rb")) 

現在,您可以修改字典和再次使用pickle.dump

-1

是否有可能載入內存中的所有帳戶保存呢?如果是的話,最簡單的方法是加載和寫的內容爲JSON:

from ast import literal_eval 
with open("in.txt") as f: 
    d = {} 
    for line in f: 
     ds = [literal_eval(ele + "}") for ele in line.split("}") if ele] 
     for _d in ds: 
      d.update(_d) 
    print(d) 

,這將給你:

import json 
with open("accounts.txt", "r") as fp: 
    accounts = json.load(fp) 
accounts["newUser"] = "password" 
with open("accounts.txt", "w") as fp: 
    json.dumps(accounts, fp) 
2

如果您的格式總是喜歡貼,您可以通過拆分解析成類型的字典:

{'account2': 'password', 'account1': 'password'} 

當你想保存請你幫個忙,並使用JSON或鹹菜即:

from json import dump, load 

dump(d, open("in.txt","w")) 

然後只需加載它,當你需要它:

d = load(open("in.txt"))) 
0

如果打開字典的字符串表示回字典和更新,你的方法將工作:

#!python3 
import ast 

try: 
    with open('accounts.txt') as f: 
     accounts=ast.literal_eval(f.read()) 
except FileNotFoundError: 
    accounts = {} 

username = input('User name? ') 
password = input('Password? ') 
accounts[username] = password 

with open('accounts.txt','w') as f: 
    f.write(str(accounts)) 

例子:

C:\>test 
User name? account1 
Password? password 

C:\>type accounts.txt 
{'account1': 'password'} 

C:\>test 
User name? account2 
Password? password 

C:\>type accounts.txt 
{'account1': 'password', 'account2': 'password'}