Write and Read a Dictionary into TXT file in Python
Categories: Tech | Pubby Cash Received:
I've been exploring an elegant way of exporting/importing a dictionary into/from an external TXT file for recording purposes.
Say I have a dictionary with stocks codes and prices, and the dictionary's name is called stocks, and this dictionary is stored in a py file called rank.py. The txt file I've like to export to is 'stocks.txt'. The relative path from the operating py file to the txt file is 'static/stocks.txt'.
To export the dictionary from the py file into the txt file, this code will be neat:
from rank import stocks
with open('static/stocks.txt', 'w') as f:
print(stocks, file=f)
To read the dictionary from the txt file, use this code:
with open('static/stocks.txt', 'r') as f:
content = f.read()
stocks = eval(content)
When it comes to the operation in flask route functions, I found it worked totally different with regard to the file path of the txt file. An error of "no file/file directory" keeps blowing off the code. Eventually I figured out that the file path should be written in a different way with the following code:
import os
from flask import current_app
f_path = os.path.join(current_app.root_path, 'static/stocks.txt')
with open(f_path, 'r') as f:
content = f.read()
stocks = eval(content)
What a tricky debugging issue!
Published from: Pennsylvania US
Liked by: Andy Tang, Evan Tang, fnfOzvSR