I have created a python script that reads a variable FILTER
from files in a folder and puts the result on screen. However, there are 4 types of variables and I would like this script to separate them all to the corresponding folders. Like move all of the files to a folder named "V" if they have variable FILTER = V
, if they have FILTER = B
, then move all of the B
ones to folder named "B" The script below works to see which files have which filter on screen.
import glob
import pyfits
import shutil
myList = []
for fitsName in glob.glob('*.fits'):
hdulist = pyfits.open(fitsName)
b = hdulist[0].header['FILTER']
c = b
myList.append(c)
hdulist.close()
for item in sorted(myList):
print item
Result on screen:
B
B
B
V
V
V
R
R
R
I
I
I
now with shutil the code i run;
import os
import glob
import pyfits
import shutil
myList = []
for fitsName in glob.glob('*.fits'):
hdulist = pyfits.open(fitsName)
hdu = hdulist[0]
prihdr = hdulist[0].header
a = hdulist[0].header['FILTER']
b = a
if b == "B":
shutil.move('/home/usr/Desktop/old/', '/home/usr/Desktop/new/B/')
myList.append(b)
hdulist.close()
Now this code works without problem but it moves all the files in Desktop/old/ to Desktop/new/B/ however, some files have b = V and other variables so what is the problem here? How can I specify the names of which files have the filters I desired so that it can automatically move?
so it is like from the code above, if c= FILTERNAME1 move to SOMEFOLDER1 if c = FILTERNAME2 move to SOMEFOLDER2 and so on.. I could not write a working code line for this so any help would be appreciated a lot.
Solution;
import os
import glob
import pyfits
import shutil
for fitsName in glob.glob('*.fits'):
hdulist = pyfits.open(fitsName)
hdu = hdulist[0]
a = hdulist[0].header['FILTER']
if a == "B":
shutil.move(fitsName, '/home/usr/Desktop/new/B/')
if a == "V":
shutil.move(fitsName, '/home/usr/Desktop/new/V/')
if a == "R":
shutil.move(fitsName, '/home/usr/Desktop/new/R/')
if a == "I":
shutil.move(fitsName, '/home/usr/Desktop/new/I/')
You can use the shutil module to move files.
shutil.move(source,destination)
Define the source file and the destination files as strings, then pass them to shutil.move()
like so:
import shutil
if c == "A":
shutil.move(source, destA)
elif c == "B":
shutil.move(source, destB)
I would also recommend that you learn how if statements work. Here are some resources: https://www.tutorialspoint.com/python/python_if_else.htm, https://www.w3schools.com/python/python_conditions.asp, https://docs.python.org/3/tutorial/controlflow.html