Python deletes a row from a large file, which is more efficient,

Source: Internet
Author: User

Python deletes a row from a large file, which is more efficient,

When processing a text in python, if you want to delete a row, the general idea is to read the file into the memory, modify it in the memory, and then write the source file.

However, if you want to process a large amount of text, such as GB-level text, this method not only requires a large amount of memory, but also takes time to read the memory at one time, and may cause memory overflow.

Therefore, another approach is required.

We can use the open () method to open the files to be modified into two files, and then read the files into the memory line by line. Find the rows to be deleted and overwrite them with the following lines one by one. See the following code for implementation.

1 with open('file.txt ', 'R') as old_file: 2 with open('file.txt', 'r + ') as new_file: 3 4 current_line = 0 5 6 # locate the row to be deleted 7 while current_line <(del_line-1): 8 old_file.readline () 9 current_line + = 110 11 # The current cursor is at the beginning of the row to be deleted, record this position 12 seek_point = old_file.tell () 13 14 # Set the cursor position 15 new_file.seek (seek_point, 0) 16 17 # Read the row to be deleted, move the cursor to the first 18 old_file.readline () 19 20 # The next row of the row to be deleted is read to next_line21 next_line = old_file.readline () 22 23 # continuously overwrite the remaining rows, and move all the following rows up one row 24 while next_line: 25 new_file.write (next_line) 26 next_line = old_file.readline () 27 28 # truncate the file after writing the last row, because of the delete operation, a row is missing for the entire file. Remove 29 new_file.truncate () from the last line of the original file ()

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.