Python programming language : quick and easy recipes

Something I used sometime and thought it should be shared with others.

List only files from a directory - ignore all subdirectories


import os
destdir='/var/tmp/testdir'
files = [ f for f in os.listdir(destdir) if os.path.isfile(os.path.join(destdir,f)) ]


Print first colums of a file e.g. 3 colums of /proc/diskstats 

DISKSTATS_FILE = '/proc/diskstats'
diskstats_file = open(DISKSTATS_FILE, 'r')
table = [line.rstrip().split() for line in diskstats_file.readlines()]
newtable = [[line[0]]+[line[1]]+[line[2]] for line in table]
newtable_3coulms = ''
for i in newtable: 
    if i == newtable[0]:
      newtable_3coulms = ' '.join(i)
    else:
      newtable_3coulms = newtable_3coulms +  '\n' + ' '.join(i)

print newtable_3coulms

diskstats_file.close()




Comments

Popular posts from this blog

Creating a package in Python

How does yaml data look when converted in python data structure?