Reputation: 139
I am trying to write my dictionary to a file and already know that I have to change it into a string. However is there any way to add '\n' at the end to keep my file organized?
code is as follows:
def dictionary(grocerystock):
with open('grocery_stock.txt','r+') as f:
lines = f.readlines()
# filter out empty lines
lines = [line for line in lines if line.strip() != '']
# split all lines
lines = [line.split() for line in lines]
# convert to a dictionary
grocerystock = dict((a, (b, c)) for a, b, c in lines)
# print
for k, v in grocerystock.items():
print (k, v)
grocerystock=str(grocerystock)
grocerystock=grocerystock.replace("{",'')
grocerystock=grocerystock.replace("}",'')
grocerystock=grocerystock.replace("(",'')
grocerystock=grocerystock.replace(")",'')
grocerystock=grocerystock.lstrip()
grocerystock=grocerystock.rstrip()
grocerystock=grocerystock.strip()
grocerystock=grocerystock.replace(":",'')
c=(grocerystock+("\n"))
e=open('grocery_stock.txt', 'w+')
e.write(c)
e.close()
Any help would be greatly appreciated.
Upvotes: 0
Views: 5295
Reputation: 89007
If your intent is to simply store the dict
to a file, you could simply use pickle, however, given your concern for readability, I would presume you want it human readable - in which case, you might want to consider JSON.
import json
with open('grocery_stock.txt', 'r') as file:
grocery_stock = json.load(file)
...
with open('grocery_stock.txt', 'w') as file:
json.dump(grocery_stock, file, indent=4)
This will produce JSON output, which looks similar to Python literals:
{
"title": "Sample Konfabulator Widget",
"name": "main_window",
"width": 500,
"height": 500
}
Naturally, structured as your data is.
Using one of these modules means you don't need to roll your own serialising/de-serialising to/from file.
Of course, if you feel you have to roll-your-own, for example, if something else (you don't control) is expecting it in this format, then you can simply concatenate a newline character to the string as you write it to the file, as you appear to have done. Does this not work as expected?
Edit:
The reason your existing code doesn't work as you expect is that you are turning the entire dictionary to a string, then adding one newline at the end - which won't solve your problem as you want a newline at the end of every line. If you had to do it manually, the best way would be to loop through your dict, writing the items out as needed:
with open('grocery_stock.txt', 'w') as file:
for key, value in grocery_stock.items():
file.write(key+" "+value+"\n")
This will write the key and value separated by a space on each line. You may need to change this to suit the data structure of the dict and the format of the output you want.
It's also worth noting your reading is done in a roundabout manner, consider:
with open('grocery_stock.txt','r') as file:
grocery_stock = {key: value for key, *value in (line.split() for line in file if line.strip())}
As I stated at the beginning however, remember this is a fragile way of serialising your data, and is reinventing the wheel - unless something else you don't control needs this format, use a standard one and save yourself the effort.
Upvotes: 7