Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7794133
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 1, 20262026-06-01T22:41:52+00:00 2026-06-01T22:41:52+00:00

I am trying to write my dictionary to a file and already know that

  • 0

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.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-01T22:41:53+00:00Added an answer on June 1, 2026 at 10:41 pm

    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.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Trying to run through a dictionary string and write the contents to file that
I'm trying to write an extension method to insert data into a dictionary of
Trying to write a couple of functions that will encrypt or decrypt a file
I am trying to write a javascript function that calls an Dictionary value and
I'm trying to load lines of a text file containing dictionary words into an
I am trying to write a Rhino Mocks test to verify that I have
I have a code that I am trying to write as block, for the
I'm trying to write a spellchecker module. It loads a text, creates a dictionary
I am trying write a function that generates simulated data but if the simulated
Trying to write a code at the moment that basically tests to see if

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.