Follow me on Twitter RSS FEED
Showing posts with label File. Show all posts
Showing posts with label File. Show all posts

PHP serialization

Recently, I was working on a PHP script for my Dad which reads some data, and will make a report on the changes of the data over time. To save the reports, I needed some way to export an array into a file and then read it back from the file in a separate script and have it exactly the same.

Thats what the serialize function does in PHP. It takes any argument, and converts it to a string. Then you can unserialize the string, and get your original object. So I just serialized my array and saved it to a file:


$string = serialize($array);
file_put_contents("saved_data.txt");


and saved it to a text document, and when I wanted to access the data:


unserialize(file_get_contents("saved_data.txt"));


If you have more than one object you want to serialize, you can put all of it in an array, and serialize the array.


$string_1 = "Hello World";
$string_2 = "What are you doing?";
$string_12 = serialize(array($string_1,$string_2))

Python Project: Recursive File Scanner

My harddrive was filling up, so I wanted to find the biggest files on my computer. I thought python would be the perfect language to do this, so I wrote a little script. The script starts in drive C:\, and recursively scans through every directory and file on your computer. If any file is larger than one Gigabyte, then it is put in a list. After every file has been scanned, then the program prints out the list of files larger than a Gigabyte. This is very useful for finding big files to clear your hard drive. Here is the code:


    import os


    def listdir(path):
        good = []
        try:
            files = os.listdir(path)
            count = 0
            for i in files:
                filepath = os.path.join(path,files[count])
                byte = os.path.getsize(filepath)
                gigabyte = byte / 1073741824
                if(gigabyte >= 1):
                    good.append(filepath + "  --  " + str(gigabyte) + "GB")
                if(os.path.isdir(filepath)):
                    bbt = 0
                    tempt = listdir(filepath)
                    for p in tempt:
                        good.append(tempt[bbt])
                        bbt += 1
                count += 1
        except WindowsError, e:
            print "Windows Error:"+str(e)
            print " -- Continuing..."
        return good


    lists = listdir("C:\\")
    count = 0
    for i in lists:
        print lists[count]
        count += 1


I am, as we [well actually just me] speak, moving quite a few GB to our MyBook.

Python Tutorial 4: File IO

Posted in

If you have worked with PHP or Perl, then file IO should be familiar. To edit/read a file, you need a file object. To get the file object, you have to open the file.

fileObject = open("file.ext", "r")
print fileObject.read()

But what if you wanted to start reading from the middle of the file? In python, this is possible. To set the file read cursor, you must use the seek function:

fileObject.seek(offset,where)

where is optional, and it tells the compiler where to start from in the file. If where is 0, then it puts the cursor at offset characters from the start of the file. If it is 1, the characters are counted form where the cursor is currently. If 2, then they are counted from the end of the file. If where is not specified, then the compiler uses 0.

The offset [as previously explained] tells the compiler how far from where to set the cursor. Negative numbers are acceptable

  • fileObject.seek(15,0) would move the cursor 15 characters from the beginning of the file
  • fileObject.seek(15,1) would move the cursor 15 characters to the right from its current position
  • fileObject.seek(-15,2) would move the cursor 15 characters away from the end of the file

Notice the negative sign before the fifteen in the last example.

seek, read, and open are the most basic IO functions. Lets look at some more: tell(), readline(), readlines(), write() and close()

tell() gets the position of the cursor in the file, which [as shown above] can be set with seek().

cursorPos = fileObject.tell()

The readline() function reads from the cursor position to the end of the line. The readlines() function reads from the cursor position to the end of the file, and returns an array with each line in a separate index. You will never guess what the write() function does. Ok, you might if you are really smart. Assuming you arn't really smart, I'll tell you what it does. It writes to the file. It writes at the cursor position, overwriting any characters infront of it, like if you press the Insert button in Microsoft Word and type. The close() function closes the file object so you can't read or write to it anymore without reopening the file. You should always remember to do this because if you don't, then the changes you made most likely won't effect the file.

Now lets talk about pickles. No I'm not being random; Pickles are a way in python to save objects to files. You can save almost any object to a file with pickles. Inorder to use them, though, you have to import them with the statement: import pickle. Then you use the pickle.dump() function to save them to the file:

import pickle
numbers = ["one",2,"three","four",5,"can you count?"]
fileObject = open("numbers.txt", "w")
pickle.dump(numbers,fileObject)
fileObject.close()

To read a pickle back in, you use the pickle.load() function:

import pickle
fileObject = open("numbers.txt", "r")
numbers = pickle.load(fileObject)
fileObject.close()
for item in numbers
    print item

The main con with pickles is that you can't save more than one object to a file. A way around this would be to put all the objects into an array, and then save the array to the file.

That concludes my fourth python tutorial.