Python delete row in file after reading it











up vote
-2
down vote

favorite












I python 2.7 I am reading data from file in while loop. When I successfully read row, I would like to delete this row from a file, but I dont know how to do it - Efficient way so i dont waste to much of CPU.



    read = open("data.csv", 'r')
for row in read:
#code......
if send == True:
-->delete sent line from file, and continue to loop









share|improve this question


























    up vote
    -2
    down vote

    favorite












    I python 2.7 I am reading data from file in while loop. When I successfully read row, I would like to delete this row from a file, but I dont know how to do it - Efficient way so i dont waste to much of CPU.



        read = open("data.csv", 'r')
    for row in read:
    #code......
    if send == True:
    -->delete sent line from file, and continue to loop









    share|improve this question
























      up vote
      -2
      down vote

      favorite









      up vote
      -2
      down vote

      favorite











      I python 2.7 I am reading data from file in while loop. When I successfully read row, I would like to delete this row from a file, but I dont know how to do it - Efficient way so i dont waste to much of CPU.



          read = open("data.csv", 'r')
      for row in read:
      #code......
      if send == True:
      -->delete sent line from file, and continue to loop









      share|improve this question













      I python 2.7 I am reading data from file in while loop. When I successfully read row, I would like to delete this row from a file, but I dont know how to do it - Efficient way so i dont waste to much of CPU.



          read = open("data.csv", 'r')
      for row in read:
      #code......
      if send == True:
      -->delete sent line from file, and continue to loop






      python python-2.7






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked 2 days ago









      TheUrban

      73




      73
























          2 Answers
          2






          active

          oldest

          votes

















          up vote
          0
          down vote



          accepted










          You shouldn't concern yourself about cpu usage when doing disk IO -- disk IO is very slow compared to almost any in-memory/cpu operation.



          There are two strategies to deleting from the middle of a file:




          1. writing all lines to keep to a secondary file, then renaming the secondary file to the original file name.


          2. copy the rest (tail) of the file to the beginning of the line you want to delete and then truncating x bytes off the end of the file (where x is equal to the length of the line you want to remove.



          Number 1 is usually preferred since it is easier and doesn't require any locking.



          Mayank Porwal has given you most of strategy #1. Here is how you would implement strategy #2:



          # open the file for both reading and writing in binary mode ('rb+')
          with open('rmline.txt', 'rb+') as fp:
          while 1:
          pos = fp.tell() # remember the starting position of the next line to read
          line = fp.readline()
          if not line:
          break # we reached the end of the file

          if should_line_be_skipped(line): # only you know what to skip :-)
          rest = fp.read() # read the rest of the file
          fp.seek(pos) # go to the start position of the line to remove
          fp.write(rest) # write the rest of the file over the line to be removed
          fp.truncate() # truncates at current position (end of file - len(line))
          fp.seek(pos) # return to where the next line is after deletion so we can continue the while loop





          share|improve this answer























          • Yeah, thanks, I will do it this way. Because my problem was if for example, computer crash in the middle of reading large file, when it turns up again it needs to start from beginning. But this code will do as I want it, to store in loop. Thanks! :)
            – TheUrban
            2 days ago


















          up vote
          0
          down vote













          The best and the fastest option in my opinion would be to re-write the file elsewhere without the lines you wanted to delete.



          Just have an appropriate negative condition to identify the lines which you want to keep.



          with open("data.csv", 'r'):
          with open("output.txt","w") as output:
          for row in read:
          #code......
          if not send == True:
          -->delete sent line from file, and continue to loop
          output.write(line)





          share|improve this answer























          • This: if ! send == True: is not valid Python code. Perhaps you mean if not send:.
            – khelwood
            2 days ago












          • Yes, thanks for pointing that out. Fixed.
            – Mayank Porwal
            2 days ago










          • You'll want to open the from-file in binary mode, since you're opening the to-file in binary mode..
            – thebjorn
            2 days ago











          Your Answer






          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: "1"
          };
          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: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














           

          draft saved


          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53372874%2fpython-delete-row-in-file-after-reading-it%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          2 Answers
          2






          active

          oldest

          votes








          2 Answers
          2






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          up vote
          0
          down vote



          accepted










          You shouldn't concern yourself about cpu usage when doing disk IO -- disk IO is very slow compared to almost any in-memory/cpu operation.



          There are two strategies to deleting from the middle of a file:




          1. writing all lines to keep to a secondary file, then renaming the secondary file to the original file name.


          2. copy the rest (tail) of the file to the beginning of the line you want to delete and then truncating x bytes off the end of the file (where x is equal to the length of the line you want to remove.



          Number 1 is usually preferred since it is easier and doesn't require any locking.



          Mayank Porwal has given you most of strategy #1. Here is how you would implement strategy #2:



          # open the file for both reading and writing in binary mode ('rb+')
          with open('rmline.txt', 'rb+') as fp:
          while 1:
          pos = fp.tell() # remember the starting position of the next line to read
          line = fp.readline()
          if not line:
          break # we reached the end of the file

          if should_line_be_skipped(line): # only you know what to skip :-)
          rest = fp.read() # read the rest of the file
          fp.seek(pos) # go to the start position of the line to remove
          fp.write(rest) # write the rest of the file over the line to be removed
          fp.truncate() # truncates at current position (end of file - len(line))
          fp.seek(pos) # return to where the next line is after deletion so we can continue the while loop





          share|improve this answer























          • Yeah, thanks, I will do it this way. Because my problem was if for example, computer crash in the middle of reading large file, when it turns up again it needs to start from beginning. But this code will do as I want it, to store in loop. Thanks! :)
            – TheUrban
            2 days ago















          up vote
          0
          down vote



          accepted










          You shouldn't concern yourself about cpu usage when doing disk IO -- disk IO is very slow compared to almost any in-memory/cpu operation.



          There are two strategies to deleting from the middle of a file:




          1. writing all lines to keep to a secondary file, then renaming the secondary file to the original file name.


          2. copy the rest (tail) of the file to the beginning of the line you want to delete and then truncating x bytes off the end of the file (where x is equal to the length of the line you want to remove.



          Number 1 is usually preferred since it is easier and doesn't require any locking.



          Mayank Porwal has given you most of strategy #1. Here is how you would implement strategy #2:



          # open the file for both reading and writing in binary mode ('rb+')
          with open('rmline.txt', 'rb+') as fp:
          while 1:
          pos = fp.tell() # remember the starting position of the next line to read
          line = fp.readline()
          if not line:
          break # we reached the end of the file

          if should_line_be_skipped(line): # only you know what to skip :-)
          rest = fp.read() # read the rest of the file
          fp.seek(pos) # go to the start position of the line to remove
          fp.write(rest) # write the rest of the file over the line to be removed
          fp.truncate() # truncates at current position (end of file - len(line))
          fp.seek(pos) # return to where the next line is after deletion so we can continue the while loop





          share|improve this answer























          • Yeah, thanks, I will do it this way. Because my problem was if for example, computer crash in the middle of reading large file, when it turns up again it needs to start from beginning. But this code will do as I want it, to store in loop. Thanks! :)
            – TheUrban
            2 days ago













          up vote
          0
          down vote



          accepted







          up vote
          0
          down vote



          accepted






          You shouldn't concern yourself about cpu usage when doing disk IO -- disk IO is very slow compared to almost any in-memory/cpu operation.



          There are two strategies to deleting from the middle of a file:




          1. writing all lines to keep to a secondary file, then renaming the secondary file to the original file name.


          2. copy the rest (tail) of the file to the beginning of the line you want to delete and then truncating x bytes off the end of the file (where x is equal to the length of the line you want to remove.



          Number 1 is usually preferred since it is easier and doesn't require any locking.



          Mayank Porwal has given you most of strategy #1. Here is how you would implement strategy #2:



          # open the file for both reading and writing in binary mode ('rb+')
          with open('rmline.txt', 'rb+') as fp:
          while 1:
          pos = fp.tell() # remember the starting position of the next line to read
          line = fp.readline()
          if not line:
          break # we reached the end of the file

          if should_line_be_skipped(line): # only you know what to skip :-)
          rest = fp.read() # read the rest of the file
          fp.seek(pos) # go to the start position of the line to remove
          fp.write(rest) # write the rest of the file over the line to be removed
          fp.truncate() # truncates at current position (end of file - len(line))
          fp.seek(pos) # return to where the next line is after deletion so we can continue the while loop





          share|improve this answer














          You shouldn't concern yourself about cpu usage when doing disk IO -- disk IO is very slow compared to almost any in-memory/cpu operation.



          There are two strategies to deleting from the middle of a file:




          1. writing all lines to keep to a secondary file, then renaming the secondary file to the original file name.


          2. copy the rest (tail) of the file to the beginning of the line you want to delete and then truncating x bytes off the end of the file (where x is equal to the length of the line you want to remove.



          Number 1 is usually preferred since it is easier and doesn't require any locking.



          Mayank Porwal has given you most of strategy #1. Here is how you would implement strategy #2:



          # open the file for both reading and writing in binary mode ('rb+')
          with open('rmline.txt', 'rb+') as fp:
          while 1:
          pos = fp.tell() # remember the starting position of the next line to read
          line = fp.readline()
          if not line:
          break # we reached the end of the file

          if should_line_be_skipped(line): # only you know what to skip :-)
          rest = fp.read() # read the rest of the file
          fp.seek(pos) # go to the start position of the line to remove
          fp.write(rest) # write the rest of the file over the line to be removed
          fp.truncate() # truncates at current position (end of file - len(line))
          fp.seek(pos) # return to where the next line is after deletion so we can continue the while loop






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited 2 days ago

























          answered 2 days ago









          thebjorn

          12.5k44884




          12.5k44884












          • Yeah, thanks, I will do it this way. Because my problem was if for example, computer crash in the middle of reading large file, when it turns up again it needs to start from beginning. But this code will do as I want it, to store in loop. Thanks! :)
            – TheUrban
            2 days ago


















          • Yeah, thanks, I will do it this way. Because my problem was if for example, computer crash in the middle of reading large file, when it turns up again it needs to start from beginning. But this code will do as I want it, to store in loop. Thanks! :)
            – TheUrban
            2 days ago
















          Yeah, thanks, I will do it this way. Because my problem was if for example, computer crash in the middle of reading large file, when it turns up again it needs to start from beginning. But this code will do as I want it, to store in loop. Thanks! :)
          – TheUrban
          2 days ago




          Yeah, thanks, I will do it this way. Because my problem was if for example, computer crash in the middle of reading large file, when it turns up again it needs to start from beginning. But this code will do as I want it, to store in loop. Thanks! :)
          – TheUrban
          2 days ago












          up vote
          0
          down vote













          The best and the fastest option in my opinion would be to re-write the file elsewhere without the lines you wanted to delete.



          Just have an appropriate negative condition to identify the lines which you want to keep.



          with open("data.csv", 'r'):
          with open("output.txt","w") as output:
          for row in read:
          #code......
          if not send == True:
          -->delete sent line from file, and continue to loop
          output.write(line)





          share|improve this answer























          • This: if ! send == True: is not valid Python code. Perhaps you mean if not send:.
            – khelwood
            2 days ago












          • Yes, thanks for pointing that out. Fixed.
            – Mayank Porwal
            2 days ago










          • You'll want to open the from-file in binary mode, since you're opening the to-file in binary mode..
            – thebjorn
            2 days ago















          up vote
          0
          down vote













          The best and the fastest option in my opinion would be to re-write the file elsewhere without the lines you wanted to delete.



          Just have an appropriate negative condition to identify the lines which you want to keep.



          with open("data.csv", 'r'):
          with open("output.txt","w") as output:
          for row in read:
          #code......
          if not send == True:
          -->delete sent line from file, and continue to loop
          output.write(line)





          share|improve this answer























          • This: if ! send == True: is not valid Python code. Perhaps you mean if not send:.
            – khelwood
            2 days ago












          • Yes, thanks for pointing that out. Fixed.
            – Mayank Porwal
            2 days ago










          • You'll want to open the from-file in binary mode, since you're opening the to-file in binary mode..
            – thebjorn
            2 days ago













          up vote
          0
          down vote










          up vote
          0
          down vote









          The best and the fastest option in my opinion would be to re-write the file elsewhere without the lines you wanted to delete.



          Just have an appropriate negative condition to identify the lines which you want to keep.



          with open("data.csv", 'r'):
          with open("output.txt","w") as output:
          for row in read:
          #code......
          if not send == True:
          -->delete sent line from file, and continue to loop
          output.write(line)





          share|improve this answer














          The best and the fastest option in my opinion would be to re-write the file elsewhere without the lines you wanted to delete.



          Just have an appropriate negative condition to identify the lines which you want to keep.



          with open("data.csv", 'r'):
          with open("output.txt","w") as output:
          for row in read:
          #code......
          if not send == True:
          -->delete sent line from file, and continue to loop
          output.write(line)






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited 2 days ago

























          answered 2 days ago









          Mayank Porwal

          2,5341620




          2,5341620












          • This: if ! send == True: is not valid Python code. Perhaps you mean if not send:.
            – khelwood
            2 days ago












          • Yes, thanks for pointing that out. Fixed.
            – Mayank Porwal
            2 days ago










          • You'll want to open the from-file in binary mode, since you're opening the to-file in binary mode..
            – thebjorn
            2 days ago


















          • This: if ! send == True: is not valid Python code. Perhaps you mean if not send:.
            – khelwood
            2 days ago












          • Yes, thanks for pointing that out. Fixed.
            – Mayank Porwal
            2 days ago










          • You'll want to open the from-file in binary mode, since you're opening the to-file in binary mode..
            – thebjorn
            2 days ago
















          This: if ! send == True: is not valid Python code. Perhaps you mean if not send:.
          – khelwood
          2 days ago






          This: if ! send == True: is not valid Python code. Perhaps you mean if not send:.
          – khelwood
          2 days ago














          Yes, thanks for pointing that out. Fixed.
          – Mayank Porwal
          2 days ago




          Yes, thanks for pointing that out. Fixed.
          – Mayank Porwal
          2 days ago












          You'll want to open the from-file in binary mode, since you're opening the to-file in binary mode..
          – thebjorn
          2 days ago




          You'll want to open the from-file in binary mode, since you're opening the to-file in binary mode..
          – thebjorn
          2 days ago


















           

          draft saved


          draft discarded



















































           


          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53372874%2fpython-delete-row-in-file-after-reading-it%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          android studio warns about leanback feature tag usage required on manifest while using Unity exported app?

          SQL update select statement

          'app-layout' is not a known element: how to share Component with different Modules