Useful information for people (aka me) teaching themselves python by writing small python aps.

21 02 2008

I have been writing a one or two small python scripts to do some useful stuff the last couple of days and since I don’t much about python learning a few things along the way. Here is some of the small things I had to lookup. The free book “Dive Into Python” by Mark Pilgrim was very useful you can read it here or see if it is included in your distro on Ubuntu the .hlm version was installed here.

Date and Time

You need to import: import datetime

To get the date and time and put it in variable date_time:

date_time = datetime.datetime.now()

Output with print date_time: “Thu Feb 21 11:36:31 2008″

To get the difference between to dates:

date1 = datetime.datetime.now()

later_date = datetime.datetime.now()

dif_date = later_date - date1

dif_date.seconds

dif_date.days

dif_date.microseconds

Output with print dif_date.microseconds:

String and Int

To declare a string:
mystring = "Hi"
To declare a int:
myint = 1

To output a string and int on same line using print command:

print "Going to print string and Int, String: "+mystring+" and Int: "+str(myint)

Lists

Declare empty list:
mylist = []

Declare list with some values (items):
mylist = ["val1","val2",4,8]

Print all items in list:
for val in mylist:
print val

Add item to list:
mylist.append("new_value")

Remove item from list:
mylist.remove("new_value")

Remove duplicate items from list:
for item in mylist:
ocurence = mylist.count(item) #number of times item occurs
for x in range(ocurence-1) : #remove all occurences exept one (-1)
mylist.remove(file)

Files and Directories
Might need to import: import shutil for copying
Get file extension:
ext = os.path.splitext("/home/fredre/test.txt")[1]
If directory does not exist create directory:
if not os.path.isdir("/home/fredre/test"):
os.mkdir("/home/fredre/test")

Copy file to another directory:
shutil.copy("/home/fredre/test.txt","/home/fredre/test")
Print all files in directory recursively:
for dirs in walk:
if(dirs[2]):
for file in dirs[2]:
working_file = os.path.join(dirs[0],file)
print working_file

Other stuff
Execute command on host operating system and display output from that command
You need to import: import commands
for out in commands.getstatusoutput("ls -l /home/fredre"):
print out


Actions

Information

Leave a comment