Question : Modulize python script

i have a script in python that i would like to modularize.  Create a def process for it.  So that i dont have to create another one for different file names and extensions.
Code Snippet:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
#!/usr/bin/env python
 
import glob,os
co_source_dir = '/u02/data/Telcordia/Processed'
os.chdir(co_source_dir)
files = glob.iglob('AZTC*.csv')
 
        for fn in files:
        year = fn[-16:-16+4]
        month = fn[-12:-12+2]
        day = fn[-10:-10+2]
 
        os.renames(fn,"%s/%s/%s/%s"%(year,month,day,fn))
        print "%s/%s/%s/%s"%(year,month,day,fn)
        break
Open in New Window Select All

Answer : Modulize python script

Not sure if I understand... if you cd to the source directory before you run the script, you don't need to use chdir(). You can use sys.argv[1] to read a parameter from the command line. Store the script in the source dir, and call it like this:

> python scriptname.py AZTC*.csv

...or store it somewhere else, and call it like this:

> python /path/to/script/scriptname.py AZTC*.csv

You can also use it from other python scripts:

import scriptname
scriptname.process('XYZ*.ext')
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
import glob,os,sys
 
def process(pattern):
    files = glob.iglob(pattern)
    for fn in files:
        year = fn[-16:-16+4]
        month = fn[-12:-12+2]
        day = fn[-10:-10+2]
        os.renames(fn,"%s/%s/%s/%s"%(year,month,day,fn))
        print "%s/%s/%s/%s"%(year,month,day,fn)
        
if __name__=='__main__':
    if len(sys.argv)<2:
        print "Move files to sub-folders.\n\nSyntax: python %s "%(sys.argv[0])
    else: 
        process(sys.argv[1])
Open in New Window Select All
Random Solutions  
 
programming4us programming4us