Code Comments

Code Comments

Tips and short tutorials on various programming technologies

Code Comments RSS Feed
 
 
 
 

Archive for Python

Get File Name from File Path in Python

Let’s say you did a search for files matching a certain pattern in a directory using Python:

import glob
 
filePaths = glob.glob("C:\\Temp\\*.txt")
print filePaths

This will list the full file paths with a .txt extension in the C:\Temp directory. For example: C:\\Temp\\test.txt.
But if you wanted to get just the file name, how would you go about that? It took [...] Read more »

Minimum or Maximum Float Value in Python 2.5

In Python 2.5, there is a built-in function that tells you the maximum allowable int value:

import sys
print sys.maxint

But there is no corresponding function to do this for float values. Part of the reason may be that it can vary from system to system. But actually, I believe they added this in version 2.6. So this [...] Read more »

How to List All Methods in a Python Object

Suppose you have an object in Python that you retrieved from a third-party library, but you don’t have access to the source code or to very good documentation. Believe me, it happens (and did to me today). You can use a simple built-in method in Python to find out which methods are exposed by a [...] Read more »

Invoke External Application in Java

I recently had a scenario where part of what I wanted to do was in Java, and the other part was in an application that was written in Python. Rather than than rewrite my entire code base in one language or the other, I wanted to find a (quick and dirty) way to invoke the [...] Read more »

“Last Index Of” for Python Strings

In Java and C#, there is a method that enables you to find the last occurrence of a given sequence of string characters within a string. This method is sometimes called “lastIndexOf.” A method by this name does not exist in Python. But there is an easy way to do it if you know what [...] Read more »

Creating a Reverse Sequence of Numbers in Python

Let’s say you want to create a sequence of numbers in reverse order (for example, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1). I tried to do this with the range function, but I couldn’t find a way to do it. But Python has a built-in function called reversed that allows you to [...] Read more »

Find the Mean/Average of a Number List in Python

To my knowledge, there is no built-in function in Python to find the mean of a list of numbers. You can use statistics packages to do this, such as statpy, but if you just want a lightweight solution to do the trick you can use the function below. Note that on the first line I [...] Read more »

Find the Class of a Python Object

Sometimes you are working with an object in Python, and because Python is not a strongly typed language, you don’t always know which class it is an implementation of. A quick way to find out is to use the type method, which can be invoked on any object and gives you a String representation of [...] Read more »

How to Override toString() in Python

In popular object-oriented languages such as Java and C#, they have a built-in method to each class that allows you to obtain a String representation of that class. They call these methods toString() or ToString(), respectively. You can use the default implementation, which basically gives you the name of the class (not usually very helpful). [...] Read more »

Python Yield Example

In Python, there is a bit of functionality that makes it convenient at times to process data while it is being processed inside another method. For example, let’s say you are searching for files within a directory that match a certain pattern, but you don’t want to wait the full time for the files to [...] Read more »

Search for Files in Directories Recursively in Python

Let’s say you want to search for files in a directory tree of files and directories. And suppose you want to search for all .zip files. You can do this from within Python by looping through the folders and trying to find files that match the *.zip wildcard pattern.
Here is some code I copied from [...] Read more »

How to Invoke a Method Dynamically in Python (Reflection)

Sometimes you want to be able to invoke a method dynamically rather than calling it explicitly. Or in other words, let’s say you have a bunch of methods, and you have a string object telling you which method to execute, but rather than doing a bunch of if statements you want to be able to [...] Read more »

Cast a List from One Type to Another in Python

One of the key properties of Python is that it is a weakly typed language. In contract to strongly typed languages such as Java, you don’t have to define the class of an object when you instantiate it. This offers much flexibility. But sometimes you want to be able to define precisely what class of [...] Read more »

Easy Way to Append PDF Files Programmatically in Python

Recently I had a bunch of one-page PDF documents that I wanted to be able to paste together so I can read them all as a single document. It turns out this is possible to do with Adobe Acrobat (which makes sense), but you have to pay for this product, and I wanted to do [...] Read more »

How to Properly Sort Strings Containing Numbers in Python

Let’s say you have a list of strings and want to be able to sort them. Python makes this extremely easy to do, which is something I really love about it.

x = ["abc", "def", "aaa"]
x.sort() // would result in [’aaa’, ‘abc’, ‘def’]

But what if you have numbers embedded in those strings? Most of us have [...] Read more »

List Files in Directory Using Wildcards With Python

Let’s say you are trying to retrieve the names of a bunch of files in a given directory that match a specific pattern. You can do this pretty easily at the command line using a command such as the following in Windows.

dir *.txt

Or something like this in Linux:

ls *.txt

But if you want to do this [...] Read more »

How to Encrypt and Decrypt Files in Python

If you want to be able to encrypt and decrypt files with Python, you might check out the following sites:
http://www.dlitz.net/software/pycrypto/
http://www.amk.ca/python/code/crypto.html
However, if you know you’re going to only be using Linux, I recommend doing file encryption as explained in this post. You can invoke commands at the command line by following the explanation here. Read more »

How to Modify PYTHONPATH on Linux

When you are installing modules in Python that need to be available to Python scripts stored in various locations on the server, you can use PYTHONPATH to specify where those resources are on the server. This environment variable tells Python where to find those modules/libraries.
This post explains how to set environment variables in Linux. You [...] Read more »

How to Generate a Sequence of Numbers in Python

Let’s say you want to generate a sequence of numbers from 1 to 10 in Python. Here’s how:

x = range(1, 11) // it goes up to one less than the second parameter

Let’s say you want to generate a sequence from 0 to 10:

x = range(11) // default is to start at 0 Read more »

How to Run Python Scripts from the Command Line in Windows

After installing Python and creating a script, all you have to do is open the command prompt and type the name of the script file (and pass any parameters to the script after that).
For example, in Windows XP, you would go to the Start menu, click on Run…, and enter cmd. Then you would need [...] Read more »