-2
import os.path                    
class Menu:
    dic={}
    def buildMenu(self):
        file = "C:/Users/zz/Desktop/Class/menu.txt" 
        if os.path.isfile(file):
            pass
        else:
            f=open("C:/Users/zz/Desktop/Class/menu.txt" ,"w")
            name=input("Enter menu name")
            while name!="":
                price=input("Enter the price")
                f.write(name+":"+price+"\n")
                name=input("Enter menu name")
            f.close()
        
        f=open("C:/Users/zz/Desktop/Class/menu.txt" ,"r")
        line=f.readline() 
        while line:
            s=line.split(':')
            print(s)
            self.dic[s[0]]=s[1]
            line=f.readline()
            # s=line.split(':')
            # self.dic[s[0]]=s[1]
        f.close()
    
    def showMenu(self):
        for x,y in self.dic.items():
            print(x+':'+y)

        print(self.dic.items())
menu=Menu()
menu.buildMenu()
menu.showMenu()

I want line break after input codes.

SO I wrote f.write(name+":"+price+"\n")

My code works well.

If I print one line, \n is not printing so it is fine.

But print the whole dictionary, \n appears.

Also, \n is not saved in menu.txt.

How can I remove \n in the dictionary?

Kim
  • 3
  • 1
  • 1
    The problem probably is that s[1] contains a newline, and the print also contains newlines. You could change your code in the while as follows: `self.dic[s[0]]=s[1].rstrip()` – Marko Nov 26 '20 at 07:41
  • you can try with this: for line in f.readlines(): print(data.rstrip()) – Malo Nov 26 '20 at 07:47
  • You said "`\n` is not saved in menu.txt". Of course it is saved. Do you expect the text `\n` to appear in the file? `"\n`" is just one character and that character is a newline. So if you have multiple lines in your file the `"\n"` is written. – Matthias Nov 26 '20 at 08:21
  • And this `line=f.readline()` stuff with the `while` loop is overly complex. A file is iterable. Drop those `line=f.readline()` lines and replace the `while line:` with `for line in f:`. – Matthias Nov 26 '20 at 08:27

3 Answers3

0

In this part of your code, you could try this change. There are comments -

def buildMenu(self):
    file_content = [] # list for file data to be written
    file = "C:/Users/zz/Desktop/Class/menu.txt" 
    if os.path.isfile(file):
        pass
    else:
        f=open("C:/Users/zz/Desktop/Class/menu.txt" ,"w")
        name=input("Enter menu name")
        while name!="":
            price=input("Enter the price")
            file_content.append(name+":"+price) # append to list the file info
            f.write(name+":"+price) # write to file without the \n
            name=input("Enter menu name")
            f.close()

The file_content will have the data without the newline in the original code.

etch_45
  • 792
  • 1
  • 6
  • 21
  • And how do you differentiate between multiple entries in the file now? – Matthias Nov 26 '20 at 08:22
  • Based on the question, the issue was that the `\n` was occurring in the dictionary. By removing `\n` from the `f.write(...)` that'd handle it. – etch_45 Nov 26 '20 at 08:27
  • I wouldn't call destroying data to have correct data at another place a good solution. But it's up to the asker to decide if they like the solution. – Matthias Nov 26 '20 at 08:29
0

The problem is that you opened the file for writing so every time you use f.write() you rewrite all the file, you have to open it for appending open("file.txt", "a") then if you want to clear it f.truncate() and onli then use f.write()

Leonardo Scotti
  • 1,069
  • 8
  • 21
0

I rewrote the whole class to demonstrate how it could be done. The main point is the seperating of tasks. Adding entries, saving and loading are different things.

The original problem is tackled in the line self.entries[name] = price.rstrip() where we remove whitespace characters from the end of price with rstrip.

import os.path


class Menu:
    def __init__(self, filename=None):
        if filename is None:
            filename = "C:/Users/zz/Desktop/Class/menu.txt"
        self.filename = filename
        self.entries = {}

    def add_entries(self):
        name = input('Enter menu name')
        while name != '':
            price = input('Enter the price''')
            self.entries[name] = price
            name = input("Enter menu name")

    def file_exists(self):
        return os.path.isfile(self.filename)

    def load(self):
        self.entries = {}
        with open(self.filename, 'r', encoding='UTF-8') as menufile:
            for line in menufile:
                name, price = line.split(':')
                self.entries[name] = price.rstrip()

    def save(self):
        with open(self.filename, 'w', encoding='UTF-8') as menufile:
            for name, price in self.entries.items():
                menufile.write(f'{name}:{price}\n')

    def show(self):
        for name, price in self.entries.items():
            print(f'{name}:{price}')


def main():
    menu = Menu()
    menu.add_entries()
    menu.save()
    menu.show()

    menu = Menu()
    menu.load()
    menu.add_entries()
    if not menu.file_exists():
        menu.save()
    menu.show()


if __name__ == '__main__':
    main()

In my own code I wouldn't use input in the class, but I left it as it is.

Matthias
  • 12,873
  • 6
  • 42
  • 48