Thread: Help Read file

    #1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2012
    Posts
    11
    Rep Power
    0

    Help Read file


    Hello, im trying to write a fuction in python to open a file read from offset bytes to size bytes and print it but if a file is very large i want it to split in 4096 bytes pieces but so far i havent figured out how to do it , i got this so far

    python Code:
     
    def read_file(filename, offset, size):
        input = open(filename)
        input.seek(offset)
        file_piece = input.read(size)
        print file_piece
  2. #2
  3. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,854
    Rep Power
    481
    Code:
    def read_file(fileobject, offset, size=None):
        if None == size:
            size = offset + 4096
        elif size < offset:
            size == offset
        fileobject.seek(offset)
        return fileobject.read(size-offset)
    This code does what you asked (except that I didn't actually test it). I'm 95% certain that your question doesn't represent what you wanted to learn.
    [code]Code tags[/code] are essential for python code and Makefiles!
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2012
    Posts
    11
    Rep Power
    0

    Edited


    Thread closed
    Last edited by walava; April 2nd, 2013 at 05:36 PM. Reason: Personal
  6. #4
  7. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,854
    Rep Power
    481
    You could make an iterator:
    Code:
    def read_file_blocks(filename, blocksize=4096):
        with open(filename) as inf:
            while True:
                result = inf.read(blocksize)
                if result:
                    yield result
                else:
                    break
    
    for block in read_file_blocks(filename):
        use_the(block)

    Comments on this post

    • walava agrees
    [code]Code tags[/code] are essential for python code and Makefiles!
  8. #5
  9. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2012
    Posts
    11
    Rep Power
    0
    Thank you for your reply it really helped me a lot . oh btw i hope im not breaking any rules but i wanted to ask you how can i know if '\n' this char is on a string what i thought was this but for some reason not working

    python Code:
     
    buffer = 'somerandom string'
    if("\n" in buffer):
        do something


    or also

    python Code:
     
    if(buffer.find("\n") != -1):
        do something

    but neither of that is working it doesnt even go into the if sentence but any other thing it takes like '/n' thats correct so how should i search if "\n" is in string or not?
    Looking for your reply

IMN logo majestic logo threadwatch logo seochat tools logo