[英]Can't write variables/dictionary to text file - python
我正在嘗試記錄一些數據,但是無論我做什么,我似乎都無法將變量寫入文件......我可以獲得一個標准字符串來寫入,但不是變量。
# in my actualy implementation toLog is meant to copy another nested dictionary but python only refrences it
toLog = NestedDictionary
# toLog = {'bought': {nestedDict}, 'sold':{nestedDict}}
# this line will work however the original data will not although it prints to console
#toLog = {'bought': {1:1, 2:2, 3:3, 4:4}, 'sold':{1:1, 2:2, 3:3, 4:4}}
file = open(filename, 'w')
file.write("trades:\nbought:")
for price, amount in toLog['bought'].items():
print(f"sanity check: {price} : {amount}")
file.write(str(price) + " : " + str(amount) + "\n")
toLog = {'bought': {}, 'sold':{}}
這會產生一個文件
trades:
bought:
但不再有,值/變量打印到控制台,但我無法讓它們寫入文件
我也試過
# in my actualy implementation toLog is meant to copy another nested dictionary but python only refrences it
toLog = NestedDictionary
# toLog = {'bought': {nestedDict}, 'sold':{nestedDict}}
# this line will work however the original data will not although it prints to console
toLog = {'bought': {1:1, 2:2, 3:3, 4:4}, 'sold':{1:1, 2:2, 3:3, 4:4}}
with open(filename, 'w') as file:
print('trades:\nbought:', file=file)
for price, amount in toLog['bought'].items():
print(f"sanity check: {price} : {amount}")
print(f"{price} : {amount}", file=file)
toLog = {'bought': {}, 'sold':{}}
產生相同的結果。
給你兩個選擇。 第一個是純文本,第二個是 json。 我沒有在 json 中添加“交易:”,但您可以將其添加為第一個 dict 鍵,它會在那里。
import json
fn = "test_output.txt"
fn2 = "test_output.json"
toLog = {'bought': {1:1, 2:2, 3:3, 4:4}, 'sold':{1:1, 2:2, 3:3, 4:4}}
output_txt = "trades:"
for log_key, log_vals in toLog.items():
output_txt += f"\n{log_key}:"
for nested_key, nested_val in log_vals.items():
output_txt += f"\n{nested_key}:{nested_val}"
# Gives you the text output like you described above
with open (fn, 'w') as f:
f.write(output_txt)
# Gives you a json output which is common for dict data
with open (fn2, 'w') as f2:
f2.write(json.dumps(toLog, indent=4))
最初我的代碼不包含導致此問題的錯誤,它已被編輯以包含它。
我的問題是我正在清理字典。 最初我認為在寫入文件后在最后執行清除操作是安全的,但似乎情況並非如此,即使它將正確的值打印到控制台,我也不知道為什么。
但是,如果其他人遇到此問題,解決方案似乎是創建需要copy
庫的深層副本。
import copy
toLog = copy.deepcopy(stuffToLog)
with open(filename, 'w') as file:
print('trades:\nbought:', file=file)
for price, amount in toLog['bought'].items():
print(f"sanity check: {price} : {amount}")
print(f"{price} : {amount}", file=file)
toLog = {'bought': {}, 'sold':{}}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.