我有一個 PYQT5 UI,它允許用戶將值存盤到串列、int 和 qttextedit 中(允許用戶撰寫為代碼編輯器。然后我將現有值保存到 txt 檔案中,因此在用戶更改值后總是可以回傳并從本地檔案。我面臨的問題是當我分配回來時,它變成了一個字母一個字母,即使分配回UI的代碼也會有\n。我也嘗試將它們變成一個串列,但結果仍然很糟糕。所以我認為保存放入 txt 是一個壞主意,我尋找了泡菜,但不確定它是否可以使用或在這種情況下如何使用。
score = 22
ocount = 88
scenario = {something here already}
...
usercode = 'var game = 0;\n if (game > 3){gid = 22}'
#List, int, dict, str store to txt file
with open(configName ".txt", 'w') as f:
f.write(repr(score) "\n" \
repr(ocount) "\n" \
repr(option) "\n" \
repr(option_ans) "\n" \
repr(matchname) "\n" \
repr(scenario) "\n" \
repr(_Options) "\n" \
repr(_Optionselected) "\n" \
repr(eInfo) "\n" \
repr(sVar) "\n" \
repr(cusotm) "\n" \
repr(survey1) "\n" \
repr(survey_ans) "\n" \
repr(eInfoName) "\n" \
repr(sVarName) "\n" \
repr(tempcode) "\n" \
repr(usercode))
輸出值如下:
2
1
['q1_a1', 'q1_a2', 'q2_a1']
['q1_a1_ans', 'q1_a2_ans', 'q2_a1_ans']
['log1', 'log2']
{'log1': 'if (q1_a1) scores.team1 - 1q1_a1_ans== "23234"){\nproduct_ids = [11,22];\n}', 'log2': 'if (scores.team2 != 11\nproduct_ids = [33,2];\n}'}
['var q1_a1 = 11;', 'var q1_a2 = 11122;', 'var q2_a1 = 2;']
['var q1_a1_ans = 22;', 'var q1_a2_ans = 222;', 'var q2_a1_ans = 2;']
['123']
['321']
['cam1']
['q1_a1', 'q1_a2', 'q2_a1']
['q1_a1_ans', 'q1_a2_ans', 'q2_a1_ans']
['123']
['321']
' \nelse if (\nelse if (\nelse if (\nelse if ('
'var has_answer = function (answer) {\n return indexOf(answer) >= 0;\n };'
#Load back
tmp=[]
f = open("lo.txt", "r")
Lines = f.readlines()
for x in Lines:
tmp.append(x)
score = tmp[0]
ocount = tmp[1]
etc...
結果:
#try change to list
['[', "'", 'q', '1', '_', 'a', '1', "'", ',', ' ', "'", 'q', '1', '_', 'a', '2', "'", ',', ' ', "'", 'q', '2', '_', 'a', '1', "'", ']', '\n']

uj5u.com熱心網友回復:
使用 exec() 將字串作為代碼執行
var = ['score', 'option', 'tempcode', 'usercode']
f = open("lo.txt", "r")
Lines = f.readlines()
for i in range(0, len(Lines)):
exec(f'{var[i]} = {Lines[i]}')
# check type
exec(f'print({var[i]}, type({var[i]}))')
輸出
2 <class 'int'>
['q1_a1', 'q1_a2', 'q2_a1'] <class 'list'>
else if (
else if (
else if (
else if ( <class 'str'>
var has_answer = function (answer) {
return indexOf(answer) >= 0;
}; <class 'str'>
lo.txt
2
['q1_a1', 'q1_a2', 'q2_a1']
' \nelse if (\nelse if (\nelse if (\nelse if ('
'var has_answer = function (answer) {\n return indexOf(answer) >= 0;\n };'
或者將它們寫在 json 中,確保串列仍然是串列。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/492315.html
標籤:Python python-3.x 列表 字典 格式
上一篇:為什么我的`button.value`沒有給出任何輸出,即使按鈕包含一些文本
下一篇:命名空間字典混淆
