简体   繁体   中英

Save created file into new directory in loop

I am currently updating some files I have in a directory, with a loop, and I would like to save those file in a different directory.

Here is what I have:

from astropy.io import fits
from mpdaf.obj import Spectrum, WaveCoord
import os, glob

ROOT_DIR=input("Enter root directory : ")
os.chdir(ROOT_DIR)
destination=input("Enter destination directory : ")

fits_files = glob.glob("*.fits")

for spect in fits_files:
    spe = Spectrum(filename= spect, ext=[0,1])
    (spect_name, ext) = os.path.splitext(spect)
    sperebin = spe.rebin(57)
    sperebin.write(spect_name + "-" + "rebin" + ".fits")

With the last line sperebin.write(spect_name + "-" + "rebin" + ".fits") it is currently writing the file in the directory I'm in, and I would like it to write it directly into the destination directory, any idea how to proceed?

You don't need to or want to change directories in your script. Instead, use pathlib to simplify the creation of the new filename.

from pathlib import Path

root_dir = Path(input("Enter root directory : "))
destination_dir = Path(input("Enter destination directory : "))

# Spectrum wants a string for the filename argument
# so you need to call str on the Path object
for pth in root_dir.glob("*.fits"):
    spe = Spectrum(filename=str(pth), ext=[0,1])
    sperebin = spe.rebin(57)
    dest_pth = destination_dir / pth.stem / "-rebin" / pth.suffix
    sperebin.write(str(dest_pth))

With os.path.join you can combine directory with filename to get the file path.

sperebin.write(os.path.join(destination, pect_name + "-" + "rebin" + ".fits"))

Also with os you can check if the directory exists and create it if you want to.

if not os.path.exists(destination):
    os.makedirs(destination)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM