Create a dictionary which saves its data to file

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty margin-bottom:0;







up vote
7
down vote

favorite












Task:



The task requires creating a class (say, ConfigDict) which inherits from the dict class.



It is supposed to save its keys and values in a file.
If a file does not exist, the instance of ConfigDict should be able to create it.



Examples:



For instance, the following code:



fh=open("config.txt","w")
fh.write("key1 = 5n")
fh.write("key2 = 3n")
fh.close()
cd=ConfigDict("config.txt")
cd.items()


would generate an output dict_items([('key1', '5'), ('key2', '3')]).



If a file does not exists, it should be possible for the instance to create it and save its data inside it.



dd=ConfigDict("test.txt")
dd["keyA"] = 'testA'
dd["keyB"] = 'testB'
dd.items()


The above lines would produce dict_items([('keyA', 'testA'), ('keyB', 'testB')]) (and a print message).



My attempt:



I will greatly appreciate any comments.



class ConfigDict(dict):
def __init__(self,file):
self.file = file

try: #check if file exists
with open(self.file,"r+") as fh:
for line in fh:
key, item = line.replace(" ", "").rstrip().split("=")
dict.__setitem__(self,key,item)

except:
print("creating "+file)
fh=open(self.file,"w")
fh.close()


def __setitem__(self,key,item):
dict.__setitem__(self,key,item) #to avoid infinite loop
lines = open(self.file).read().splitlines()

for index, line in enumerate(lines):
if line.replace(" ", "").rstrip().split("=")[0] == key:
lines[index] = str(key)+" = "+str(item)
else:
lines.append(str(key)+" = "+str(item))

open(self.file,'w').write('n'.join(lines))


Corrected version



import os

class ConfigDict(dict):
def __init__(self,file):
self.file = file
if os.path.isfile(self.file):
with open(self.file,"r") as fh:
for line in fh:
key, item = line.replace(" ", "").rstrip().split("=")
dict.__setitem__(self,key,item)

def __setitem__(self,key,item):
dict.__setitem__(self,key,item)
with open(self.file, 'w') as save_file:
for key, value in self.items():
save_file.write(" = n".format(key, value))






share|improve this question



























    up vote
    7
    down vote

    favorite












    Task:



    The task requires creating a class (say, ConfigDict) which inherits from the dict class.



    It is supposed to save its keys and values in a file.
    If a file does not exist, the instance of ConfigDict should be able to create it.



    Examples:



    For instance, the following code:



    fh=open("config.txt","w")
    fh.write("key1 = 5n")
    fh.write("key2 = 3n")
    fh.close()
    cd=ConfigDict("config.txt")
    cd.items()


    would generate an output dict_items([('key1', '5'), ('key2', '3')]).



    If a file does not exists, it should be possible for the instance to create it and save its data inside it.



    dd=ConfigDict("test.txt")
    dd["keyA"] = 'testA'
    dd["keyB"] = 'testB'
    dd.items()


    The above lines would produce dict_items([('keyA', 'testA'), ('keyB', 'testB')]) (and a print message).



    My attempt:



    I will greatly appreciate any comments.



    class ConfigDict(dict):
    def __init__(self,file):
    self.file = file

    try: #check if file exists
    with open(self.file,"r+") as fh:
    for line in fh:
    key, item = line.replace(" ", "").rstrip().split("=")
    dict.__setitem__(self,key,item)

    except:
    print("creating "+file)
    fh=open(self.file,"w")
    fh.close()


    def __setitem__(self,key,item):
    dict.__setitem__(self,key,item) #to avoid infinite loop
    lines = open(self.file).read().splitlines()

    for index, line in enumerate(lines):
    if line.replace(" ", "").rstrip().split("=")[0] == key:
    lines[index] = str(key)+" = "+str(item)
    else:
    lines.append(str(key)+" = "+str(item))

    open(self.file,'w').write('n'.join(lines))


    Corrected version



    import os

    class ConfigDict(dict):
    def __init__(self,file):
    self.file = file
    if os.path.isfile(self.file):
    with open(self.file,"r") as fh:
    for line in fh:
    key, item = line.replace(" ", "").rstrip().split("=")
    dict.__setitem__(self,key,item)

    def __setitem__(self,key,item):
    dict.__setitem__(self,key,item)
    with open(self.file, 'w') as save_file:
    for key, value in self.items():
    save_file.write(" = n".format(key, value))






    share|improve this question























      up vote
      7
      down vote

      favorite









      up vote
      7
      down vote

      favorite











      Task:



      The task requires creating a class (say, ConfigDict) which inherits from the dict class.



      It is supposed to save its keys and values in a file.
      If a file does not exist, the instance of ConfigDict should be able to create it.



      Examples:



      For instance, the following code:



      fh=open("config.txt","w")
      fh.write("key1 = 5n")
      fh.write("key2 = 3n")
      fh.close()
      cd=ConfigDict("config.txt")
      cd.items()


      would generate an output dict_items([('key1', '5'), ('key2', '3')]).



      If a file does not exists, it should be possible for the instance to create it and save its data inside it.



      dd=ConfigDict("test.txt")
      dd["keyA"] = 'testA'
      dd["keyB"] = 'testB'
      dd.items()


      The above lines would produce dict_items([('keyA', 'testA'), ('keyB', 'testB')]) (and a print message).



      My attempt:



      I will greatly appreciate any comments.



      class ConfigDict(dict):
      def __init__(self,file):
      self.file = file

      try: #check if file exists
      with open(self.file,"r+") as fh:
      for line in fh:
      key, item = line.replace(" ", "").rstrip().split("=")
      dict.__setitem__(self,key,item)

      except:
      print("creating "+file)
      fh=open(self.file,"w")
      fh.close()


      def __setitem__(self,key,item):
      dict.__setitem__(self,key,item) #to avoid infinite loop
      lines = open(self.file).read().splitlines()

      for index, line in enumerate(lines):
      if line.replace(" ", "").rstrip().split("=")[0] == key:
      lines[index] = str(key)+" = "+str(item)
      else:
      lines.append(str(key)+" = "+str(item))

      open(self.file,'w').write('n'.join(lines))


      Corrected version



      import os

      class ConfigDict(dict):
      def __init__(self,file):
      self.file = file
      if os.path.isfile(self.file):
      with open(self.file,"r") as fh:
      for line in fh:
      key, item = line.replace(" ", "").rstrip().split("=")
      dict.__setitem__(self,key,item)

      def __setitem__(self,key,item):
      dict.__setitem__(self,key,item)
      with open(self.file, 'w') as save_file:
      for key, value in self.items():
      save_file.write(" = n".format(key, value))






      share|improve this question













      Task:



      The task requires creating a class (say, ConfigDict) which inherits from the dict class.



      It is supposed to save its keys and values in a file.
      If a file does not exist, the instance of ConfigDict should be able to create it.



      Examples:



      For instance, the following code:



      fh=open("config.txt","w")
      fh.write("key1 = 5n")
      fh.write("key2 = 3n")
      fh.close()
      cd=ConfigDict("config.txt")
      cd.items()


      would generate an output dict_items([('key1', '5'), ('key2', '3')]).



      If a file does not exists, it should be possible for the instance to create it and save its data inside it.



      dd=ConfigDict("test.txt")
      dd["keyA"] = 'testA'
      dd["keyB"] = 'testB'
      dd.items()


      The above lines would produce dict_items([('keyA', 'testA'), ('keyB', 'testB')]) (and a print message).



      My attempt:



      I will greatly appreciate any comments.



      class ConfigDict(dict):
      def __init__(self,file):
      self.file = file

      try: #check if file exists
      with open(self.file,"r+") as fh:
      for line in fh:
      key, item = line.replace(" ", "").rstrip().split("=")
      dict.__setitem__(self,key,item)

      except:
      print("creating "+file)
      fh=open(self.file,"w")
      fh.close()


      def __setitem__(self,key,item):
      dict.__setitem__(self,key,item) #to avoid infinite loop
      lines = open(self.file).read().splitlines()

      for index, line in enumerate(lines):
      if line.replace(" ", "").rstrip().split("=")[0] == key:
      lines[index] = str(key)+" = "+str(item)
      else:
      lines.append(str(key)+" = "+str(item))

      open(self.file,'w').write('n'.join(lines))


      Corrected version



      import os

      class ConfigDict(dict):
      def __init__(self,file):
      self.file = file
      if os.path.isfile(self.file):
      with open(self.file,"r") as fh:
      for line in fh:
      key, item = line.replace(" ", "").rstrip().split("=")
      dict.__setitem__(self,key,item)

      def __setitem__(self,key,item):
      dict.__setitem__(self,key,item)
      with open(self.file, 'w') as save_file:
      for key, value in self.items():
      save_file.write(" = n".format(key, value))








      share|improve this question












      share|improve this question




      share|improve this question








      edited Jun 24 at 19:32
























      asked Jun 23 at 19:04









      Gregory Rut

      1384




      1384




















          1 Answer
          1






          active

          oldest

          votes

















          up vote
          6
          down vote



          accepted










          bugs:



          1. Your implementation of __setitem__() does not to add a line
            if the key does not exist in the file yet.

          other issues:



          1. There is no need to create the file if it does not exist in
            __init__(), as open(..., 'w') in __setattr__() will create
            it for you.


          2. It is gennerally not a good idea to print from a data class
            (i.e. print("creating "+file)) as this makes the class unuseable for
            programs that use stdout.



          3. Iterating over a file in python automatically splits on lines so



            lines = open(self.file).read().splitlines()
            for index, line in enumerate(lines):


            could be written as



            for index, line in enumerate(open(self.file)):


            (like you did in __init__())




          4. If you are going to completly rewrite the file on every
            __setitem__(), there is no point in reading the file first, as this
            takes more time and is harder to read. here is an example
            __setitem__():



            def __setitem__(self,key,item):
            dict.__setitem__(self,key,item) #to avoid infinite loop

            with open(self.file, 'w') as save_file:
            for key, value in self.items():
            save_file.write(" = n".format(key, value))






          share|improve this answer























          • Thanks, the code will be much simpler. Regarding point 1, while I'm aware that open(...,'w') creates a file, if the try statement seemed to be a reasonable choice. If a file exists, one can set the keys and values. If it does not exist, create it and do nothing else.
            – Gregory Rut
            Jun 23 at 21:04






          • 1




            My point is that the file will be created anyways in __setattr__() so there is no reason to create it in __init__(). I have edited my answer to hopefully reflect this better.
            – Peter
            Jun 23 at 21:17










          • Ok, I think i get it:-).
            – Gregory Rut
            Jun 23 at 21:29






          • 2




            Oh and please, close the file in __setitem__. Preferably using a with statement.
            – Mathias Ettinger
            Jun 24 at 19:13






          • 3




            @GregoryRut instead of writing the whole file at each __setitem__, just write the last entry, it will take less time. Duplicate entries are taken care off just fine when reading the file. Special care has to be taken when deleting entries, hence the proposal to rewrite the file on __delitem__.
            – Mathias Ettinger
            Jun 24 at 19:52










          Your Answer




          StackExchange.ifUsing("editor", function ()
          return StackExchange.using("mathjaxEditing", function ()
          StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
          StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
          );
          );
          , "mathjax-editing");

          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "196"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          convertImagesToLinks: false,
          noModals: false,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );








           

          draft saved


          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f197129%2fcreate-a-dictionary-which-saves-its-data-to-file%23new-answer', 'question_page');

          );

          Post as a guest






























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          up vote
          6
          down vote



          accepted










          bugs:



          1. Your implementation of __setitem__() does not to add a line
            if the key does not exist in the file yet.

          other issues:



          1. There is no need to create the file if it does not exist in
            __init__(), as open(..., 'w') in __setattr__() will create
            it for you.


          2. It is gennerally not a good idea to print from a data class
            (i.e. print("creating "+file)) as this makes the class unuseable for
            programs that use stdout.



          3. Iterating over a file in python automatically splits on lines so



            lines = open(self.file).read().splitlines()
            for index, line in enumerate(lines):


            could be written as



            for index, line in enumerate(open(self.file)):


            (like you did in __init__())




          4. If you are going to completly rewrite the file on every
            __setitem__(), there is no point in reading the file first, as this
            takes more time and is harder to read. here is an example
            __setitem__():



            def __setitem__(self,key,item):
            dict.__setitem__(self,key,item) #to avoid infinite loop

            with open(self.file, 'w') as save_file:
            for key, value in self.items():
            save_file.write(" = n".format(key, value))






          share|improve this answer























          • Thanks, the code will be much simpler. Regarding point 1, while I'm aware that open(...,'w') creates a file, if the try statement seemed to be a reasonable choice. If a file exists, one can set the keys and values. If it does not exist, create it and do nothing else.
            – Gregory Rut
            Jun 23 at 21:04






          • 1




            My point is that the file will be created anyways in __setattr__() so there is no reason to create it in __init__(). I have edited my answer to hopefully reflect this better.
            – Peter
            Jun 23 at 21:17










          • Ok, I think i get it:-).
            – Gregory Rut
            Jun 23 at 21:29






          • 2




            Oh and please, close the file in __setitem__. Preferably using a with statement.
            – Mathias Ettinger
            Jun 24 at 19:13






          • 3




            @GregoryRut instead of writing the whole file at each __setitem__, just write the last entry, it will take less time. Duplicate entries are taken care off just fine when reading the file. Special care has to be taken when deleting entries, hence the proposal to rewrite the file on __delitem__.
            – Mathias Ettinger
            Jun 24 at 19:52














          up vote
          6
          down vote



          accepted










          bugs:



          1. Your implementation of __setitem__() does not to add a line
            if the key does not exist in the file yet.

          other issues:



          1. There is no need to create the file if it does not exist in
            __init__(), as open(..., 'w') in __setattr__() will create
            it for you.


          2. It is gennerally not a good idea to print from a data class
            (i.e. print("creating "+file)) as this makes the class unuseable for
            programs that use stdout.



          3. Iterating over a file in python automatically splits on lines so



            lines = open(self.file).read().splitlines()
            for index, line in enumerate(lines):


            could be written as



            for index, line in enumerate(open(self.file)):


            (like you did in __init__())




          4. If you are going to completly rewrite the file on every
            __setitem__(), there is no point in reading the file first, as this
            takes more time and is harder to read. here is an example
            __setitem__():



            def __setitem__(self,key,item):
            dict.__setitem__(self,key,item) #to avoid infinite loop

            with open(self.file, 'w') as save_file:
            for key, value in self.items():
            save_file.write(" = n".format(key, value))






          share|improve this answer























          • Thanks, the code will be much simpler. Regarding point 1, while I'm aware that open(...,'w') creates a file, if the try statement seemed to be a reasonable choice. If a file exists, one can set the keys and values. If it does not exist, create it and do nothing else.
            – Gregory Rut
            Jun 23 at 21:04






          • 1




            My point is that the file will be created anyways in __setattr__() so there is no reason to create it in __init__(). I have edited my answer to hopefully reflect this better.
            – Peter
            Jun 23 at 21:17










          • Ok, I think i get it:-).
            – Gregory Rut
            Jun 23 at 21:29






          • 2




            Oh and please, close the file in __setitem__. Preferably using a with statement.
            – Mathias Ettinger
            Jun 24 at 19:13






          • 3




            @GregoryRut instead of writing the whole file at each __setitem__, just write the last entry, it will take less time. Duplicate entries are taken care off just fine when reading the file. Special care has to be taken when deleting entries, hence the proposal to rewrite the file on __delitem__.
            – Mathias Ettinger
            Jun 24 at 19:52












          up vote
          6
          down vote



          accepted







          up vote
          6
          down vote



          accepted






          bugs:



          1. Your implementation of __setitem__() does not to add a line
            if the key does not exist in the file yet.

          other issues:



          1. There is no need to create the file if it does not exist in
            __init__(), as open(..., 'w') in __setattr__() will create
            it for you.


          2. It is gennerally not a good idea to print from a data class
            (i.e. print("creating "+file)) as this makes the class unuseable for
            programs that use stdout.



          3. Iterating over a file in python automatically splits on lines so



            lines = open(self.file).read().splitlines()
            for index, line in enumerate(lines):


            could be written as



            for index, line in enumerate(open(self.file)):


            (like you did in __init__())




          4. If you are going to completly rewrite the file on every
            __setitem__(), there is no point in reading the file first, as this
            takes more time and is harder to read. here is an example
            __setitem__():



            def __setitem__(self,key,item):
            dict.__setitem__(self,key,item) #to avoid infinite loop

            with open(self.file, 'w') as save_file:
            for key, value in self.items():
            save_file.write(" = n".format(key, value))






          share|improve this answer















          bugs:



          1. Your implementation of __setitem__() does not to add a line
            if the key does not exist in the file yet.

          other issues:



          1. There is no need to create the file if it does not exist in
            __init__(), as open(..., 'w') in __setattr__() will create
            it for you.


          2. It is gennerally not a good idea to print from a data class
            (i.e. print("creating "+file)) as this makes the class unuseable for
            programs that use stdout.



          3. Iterating over a file in python automatically splits on lines so



            lines = open(self.file).read().splitlines()
            for index, line in enumerate(lines):


            could be written as



            for index, line in enumerate(open(self.file)):


            (like you did in __init__())




          4. If you are going to completly rewrite the file on every
            __setitem__(), there is no point in reading the file first, as this
            takes more time and is harder to read. here is an example
            __setitem__():



            def __setitem__(self,key,item):
            dict.__setitem__(self,key,item) #to avoid infinite loop

            with open(self.file, 'w') as save_file:
            for key, value in self.items():
            save_file.write(" = n".format(key, value))







          share|improve this answer















          share|improve this answer



          share|improve this answer








          edited Jun 25 at 16:30


























          answered Jun 23 at 19:58









          Peter

          59410




          59410











          • Thanks, the code will be much simpler. Regarding point 1, while I'm aware that open(...,'w') creates a file, if the try statement seemed to be a reasonable choice. If a file exists, one can set the keys and values. If it does not exist, create it and do nothing else.
            – Gregory Rut
            Jun 23 at 21:04






          • 1




            My point is that the file will be created anyways in __setattr__() so there is no reason to create it in __init__(). I have edited my answer to hopefully reflect this better.
            – Peter
            Jun 23 at 21:17










          • Ok, I think i get it:-).
            – Gregory Rut
            Jun 23 at 21:29






          • 2




            Oh and please, close the file in __setitem__. Preferably using a with statement.
            – Mathias Ettinger
            Jun 24 at 19:13






          • 3




            @GregoryRut instead of writing the whole file at each __setitem__, just write the last entry, it will take less time. Duplicate entries are taken care off just fine when reading the file. Special care has to be taken when deleting entries, hence the proposal to rewrite the file on __delitem__.
            – Mathias Ettinger
            Jun 24 at 19:52
















          • Thanks, the code will be much simpler. Regarding point 1, while I'm aware that open(...,'w') creates a file, if the try statement seemed to be a reasonable choice. If a file exists, one can set the keys and values. If it does not exist, create it and do nothing else.
            – Gregory Rut
            Jun 23 at 21:04






          • 1




            My point is that the file will be created anyways in __setattr__() so there is no reason to create it in __init__(). I have edited my answer to hopefully reflect this better.
            – Peter
            Jun 23 at 21:17










          • Ok, I think i get it:-).
            – Gregory Rut
            Jun 23 at 21:29






          • 2




            Oh and please, close the file in __setitem__. Preferably using a with statement.
            – Mathias Ettinger
            Jun 24 at 19:13






          • 3




            @GregoryRut instead of writing the whole file at each __setitem__, just write the last entry, it will take less time. Duplicate entries are taken care off just fine when reading the file. Special care has to be taken when deleting entries, hence the proposal to rewrite the file on __delitem__.
            – Mathias Ettinger
            Jun 24 at 19:52















          Thanks, the code will be much simpler. Regarding point 1, while I'm aware that open(...,'w') creates a file, if the try statement seemed to be a reasonable choice. If a file exists, one can set the keys and values. If it does not exist, create it and do nothing else.
          – Gregory Rut
          Jun 23 at 21:04




          Thanks, the code will be much simpler. Regarding point 1, while I'm aware that open(...,'w') creates a file, if the try statement seemed to be a reasonable choice. If a file exists, one can set the keys and values. If it does not exist, create it and do nothing else.
          – Gregory Rut
          Jun 23 at 21:04




          1




          1




          My point is that the file will be created anyways in __setattr__() so there is no reason to create it in __init__(). I have edited my answer to hopefully reflect this better.
          – Peter
          Jun 23 at 21:17




          My point is that the file will be created anyways in __setattr__() so there is no reason to create it in __init__(). I have edited my answer to hopefully reflect this better.
          – Peter
          Jun 23 at 21:17












          Ok, I think i get it:-).
          – Gregory Rut
          Jun 23 at 21:29




          Ok, I think i get it:-).
          – Gregory Rut
          Jun 23 at 21:29




          2




          2




          Oh and please, close the file in __setitem__. Preferably using a with statement.
          – Mathias Ettinger
          Jun 24 at 19:13




          Oh and please, close the file in __setitem__. Preferably using a with statement.
          – Mathias Ettinger
          Jun 24 at 19:13




          3




          3




          @GregoryRut instead of writing the whole file at each __setitem__, just write the last entry, it will take less time. Duplicate entries are taken care off just fine when reading the file. Special care has to be taken when deleting entries, hence the proposal to rewrite the file on __delitem__.
          – Mathias Ettinger
          Jun 24 at 19:52




          @GregoryRut instead of writing the whole file at each __setitem__, just write the last entry, it will take less time. Duplicate entries are taken care off just fine when reading the file. Special care has to be taken when deleting entries, hence the proposal to rewrite the file on __delitem__.
          – Mathias Ettinger
          Jun 24 at 19:52












           

          draft saved


          draft discarded


























           


          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f197129%2fcreate-a-dictionary-which-saves-its-data-to-file%23new-answer', 'question_page');

          );

          Post as a guest













































































          Popular posts from this blog

          Greedy Best First Search implementation in Rust

          Function to Return a JSON Like Objects Using VBA Collections and Arrays

          C++11 CLH Lock Implementation