Learning Python – mkfile

I’m trying to learn Python, again, and the problem is in trying to code things which would be simple in C/Perl/etc which are hard in Python.

I talked about how cool mkfile was in Creating a small zpool for testing and so I thought I would try to code that up in Python. Remember, this is my first whack at Python in 2 years, so it is all pretty much fresh and I’m in a learning mode.

I struggled with strings, bytearrays, and bufferedreaders. I still don’t know how to open a bufferedreader.

But I finally got to a working piece of code:

import array

def mkfile(file, size) :
    chunk = 1024
    loopto = size // chunk
    filler = size % chunk

    bite = bytearray(chunk)

    try :
        f = open(file, "wb")
        for n in range(loopto) :
            f.write(bite)

        if filler > 0 :
            f.write(bytearray(filler))

    finally:
        f.close()

mkfile("h1024.out", 1024)
mkfile("h1023.out", 1023)
mkfile("h64.out", 64)
mkfile("h1025.out", 1025)
mkfile("h10250.out", 10250)

And it actually yields appropriately sized files:

[thomas@snakey src]$ ls -la h*.out
-rw-r--r-- 1 thomas wheel  1023 Feb 13 15:47 h1023.out
-rw-r--r-- 1 thomas wheel  1024 Feb 13 15:47 h1024.out
-rw-r--r-- 1 thomas wheel 10250 Feb 13 15:47 h10250.out
-rw-r--r-- 1 thomas wheel  1025 Feb 13 15:47 h1025.out
-rw-r--r-- 1 thomas wheel    64 Feb 13 15:47 h64.out

Now I need to check to see if they are all zeros:

[thomas@snakey src]$ dd if=/dev/zero of=z10250.out bs=10250 count=1
1+0 records in
1+0 records out
10250 bytes (10 kB) copied, 4.6629e-05 s, 220 MB/s
[thomas@snakey src]$ cmp z10250.out h10250.out 

So yeah, there are really easy ways to accomplish mkfile.

Leave a Reply