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

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.

Python Tutorial 3: Loops and Conditionals

Like I said in my First Python Tutorial, there are no brackets [ { and } ] ; Python uses indentation instead.

    a = 0
    while a < 10:
        a = a + 1
        print a
    print "End of loop"

Everything after the while a < 10: statement that is indented is repeated until a is no longer smaller than 10. Everytime through the loop, a is incremented, and then printed. The output of this program:

1
2
3
4
5
6
7
8
9
10
End of loop

Notice that "End of loop" is only printed once. That is because it is not indented, and hence comes after the while loop ends. Here is the basic form for the while loop:


while {condition that the loop continues}:
    {what to do in the loop}
    {have it indented, usually for spaces}
{the code here is not looped}
{because it isn't indented}




The if statement is rather similar


if(condition)
    statements
else
    statements




This can be very useful for many things


if(enteredPassword == correctPassword)
    login()
else
    print "Incorrect password";

Python Tutorial 2: Variables

Posted in
In this tutorial, we’ll study variables. Python variables are related the closest to PHP and Perl, except they don’t start with any symbols. In Python, both concatenation and addition are done with +. All the others you would expect.


+Addition / Concatenation
-Subtraction
*Multiplication
/Division
%Modulos
**Powers


Python variables are generic; you don’t have to declare them with a type [int,string,char etc...] or with var, you just simply use them. A variable can hold a number at one point, and later in the program hold a string of characters.


    varone = 5
    vartwo = 6


After assigning the variables, you can add them together and store them in another variable:


    varthree = varone + vartwo



This assigns varthree to 11. You can subtract, multiply, and divide in the same way. You can divide vartwo in half like this:

    vartwo /= 2

This takes vartwo, divides it by two, then assigns it back to vartwo. So since we had vartwo set to 6, it would now be set to 3. You can multiply by two with *=, add two with +=, subtract two with -= etc...

Strings are slightly different.

    stringone = "Hello"
    stringtwo = "World"
    greeting = stringone + " " + stringtwo


This gives the variable greeting the value "Hello World". Commas do virtually the same thing as + with strings, except commas insert spaces. The above greeting assignment does the same thing as the following:

    greeting = stringone,stringtwo