2011-06-19 29 views
6

मेरे पास टेक्स्ट के साथ बड़ी फ़ाइल (कुछ जीबी) है।बड़ी फ़ाइल में स्ट्रिंग सम्मिलन

उदाहरण के लिए, यह अगले पाठ है:

Hello, World! 

मैं 5 की स्थिति में शब्द "हास्यास्पद" डालें, और बचे हुए लेख की भरपाई करने के लिए की जरूरत है:

Hello, funny World! 

मैं कैसे डॉन कर सकते हैं ' बाकी ऑफसेटिंग के लिए सभी फाइलें नहीं पढ़ी? या मैं इस ऑपरेशन को कैसे अनुकूलित कर सकता हूं?

धन्यवाद।

+0

मुझे लगता है कि आप स्थिति 6 (शून्य-आधारित) का मतलब मानते हैं। – tzot

+0

हम्म। शायद आप ठीक है :) –

उत्तर

8

आप नहीं कर सकते। सादा पाठ फ़ाइलों को फ़ाइल के आरंभ या मध्य में संक्षिप्त या विस्तारित नहीं किया जा सकता है, लेकिन केवल अंत में।

from __future__ import with_statement 

import mmap, os 

def insert_string(fp, offset, some_bytes): 
    # fp is assumedly open for read and write 
    fp.seek(0, os.SEEK_END) 
    # now append len(some_bytes) dummy bytes 
    fp.write(some_bytes) # some_bytes happens to have the right len :) 
    fp.flush() 
    file_length= fp.tell() 

    mm= mmap.mmap(fp.fileno(), file_length) 
    # how many bytes do we have to shift? 
    bytes_to_shift= file_length - offset - len(some_bytes) 
    # now shift them 
    mm.move(offset + len(some_bytes), offset, bytes_to_shift) 
    # and replace the contents at offset 
    mm[offset:offset+len(some_bytes)]= some_bytes 
    mm.close() 

if __name__ == "__main__": 
    # create the sample file 
    with open("test.txt", "w") as fp: 
     fp.write("Hello, World!") 
    # now operate on it 
    with open("test.txt", "r+b") as fp: 
     insert_string(fp, 6, " funny") 

एनबी:

+0

द्विआधारी फाइलों के बारे में क्या? –

+0

@ रूलेक्सैक: वही। यह फ़ाइल-सिस्टम की एक सीमा है जिसका प्रयोग आम तौर पर किया जाता है। –

+0

सटीक प्रारूप पर निर्भर करता है। –

0

यदि आपकी फ़ाइल में कुछ गीगाबाइट है, तो शायद मेरी समाधान 64-बिट ऑपरेटिंग सिस्टम पर ही लागू होगी के लिए देख : यह लिनक्स पर एक पायथन 2 प्रोग्राम है। YMMV।

संबंधित मुद्दे