0

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!

2
  • You could use the os.path functions to separate the filename from the extension or, since you seem to consistently use underscores, simply do a filename.split("_") to get a list of all the parts of the filename. You can then piece it back together in a different order via the list indices. index 0 would be "Field", index 1 would be "52" and so on. You can then "_".join()` afterwards to create a new filename Commented Mar 24, 2016 at 12:54
  • Thank you to your answer. I used the split method and it's work : Commented Mar 24, 2016 at 13:00

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

3 Comments

Perfect ! Both solutions are very interesting ! This one is particulary smart !
@Astrolabe1993 This will work only if every input file has 'combined_final_roughcal' at the end though. If that's Your case use this solution because it should be a little bit faster than mine.
@Tony Babarino At the moment, all my input files have the same name. Only the field number is different about each file.
1
>>> 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')) 

1 Comment

Thank you so much ! I had the same beginning, but I was blocking on the hdu.writeto. So thank you !
1

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))

2 Comments

Your script is useful. But, I don't need to get an increment "traitement" because this string represent the result of my first script. After that, I will take the ouput files and I will execute my second script. I will obtain (for example) : Field_52_traitement_2.fits etc .. ;)
Cool cool. I just always try to make it a little generic. It might not be necessary for you, but that way you can have everything in one script and run all tests automatically in a for loop if you want.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.