scripting - How do i run python script on all files in a directory? -


import pyfits  file = input('enter file name string: ')  newfile = file.replace('.fits','.dat')  f = pyfits.getdata(file)  h = pyfits.getheader(file)  g = open(newfile,'w')  ref = h['jd_ref']  x in range (len(f)):         deltat = (f[x][0]-ref)/86400         refday = ref/86400         time = refday + deltat         mag = f[x][3]         err = f[x][4]         flag = f[x][8]         g.write('%9s %9s %10s %2s\n'% (time,mag,err,flag))   g.close() 

i trying convert .fits file containing table of data .dat file. program performs necessary functions want, performs action 1 @ time. have around 300 .fits files need converted , doing them typing in name each time painful. can select run program , cycle through , perform script on files in directory.

how can modify program run on of files in current directory?

use os.listdir(). if want return files match '.fits' pattern, can use glob.glob('*.fits').

this return files in current directory, or whatever directory supply argument. can loop on these names, , use input files. like:

for f in os.listdir():     newfile = f.replace('.fits', '.dat')     # rest of code 

Comments