Reputation: 6128
I have a question. How can I rename the output file using the input filename?
For example, my input filename is:
Field_52_combined_final_roughcal.fits
I would like to obtain an output filename like:
Field_52_traitement_1.fits
I know that I could write :
hdu.writeto('Field_52_traitement_1.fits')
But, I have an other script which loop on 200 files, and I would like the output filename being automatically generated by the input filename.
My script looks like this (for a single input file):
#!/usr/bin/python
# coding: utf-8
from astropy.io import fits
from astropy.table import Table
import numpy as np
###################################
# Fichier contenant le champ brut #
###################################
filename = 'E:/Fields/Field52_combined_final_roughcal.fits'
# Ouverture du fichier à l'aide d'astropy
field = fits.open(filename)
# Lecture des données fits
tbdata = field[1].data
#######################################################
# Application du tri en fonction de divers paramètres #
#######################################################
Several conditions / sort
###################################################
# Ecriture du résultat dans nouveau fichier .fits #
###################################################
hdu = fits.BinTableHDU(data=tbdata_final)
hdu.writeto('{}_{}'.format(filename,'traitement_1'))
But, with this kind of script, I get:
Field_52_combined_final_roughcal.fits_traitement_1
Tell me, if you have any ideas, websites or something else :) Thank you for your answers!
Upvotes: 0
Views: 4227
Reputation: 4010
Here's one way of doing it. The "best" way depends on how dynamic you want the filename to be. E.g. whether you want to increment "traitement" or not.
def create_new_filename(old_filename, traitement):
pieces = old_filename.split("_")
return "_".join([pieces[0], pieces[1], "traitement", str(traitement)]) + ".fits"
In the interpreter:
>>> print create_new_filename("Field_52_combined_final_roughcal.fits", 1)
Field_52_traitement_1.fits
To use it in your case, you'd pass in the old filename and the traitement number you want:
hdu.writeto(create_new_filename("Field_52_combined_final_roughcal.fits", 1))
Upvotes: 1
Reputation: 258
You can use a simple string replace method and create a variable for the output filename.
filename = 'E:/Fields/Field52_combined_final_roughcal.fits'
outname = filename.replace('combined_final_roughcal', 'traitement_1')
Now just write to the file named 'outname', which is now:
E:/Fields/Field52_traitement_1.fits
Upvotes: 2
Reputation: 3405
>>> filename = 'Field_52_combined_final_roughcal.fits'
>>> filename.split('_')
['Field', '52', 'combined', 'final', 'roughcal.fits']
>>> filename.split('_')[:2]
['Field', '52']
>>> '_'.join(filename.split('_')[:2])
'Field_52'
So applying that to Your code, use:
hdu.writeto('{}_{}'.format('_'.join(filename.split('_')[:2]),'traitement_1'))
instead of:
hdu.writeto('{}_{}'.format(filename,'traitement_1'))
Upvotes: 1