将创建的文件保存到循环中的新目录中

我目前正在使用循环更新目录中的一些文件,我想将这些文件保存在其他目录中。


这是我所拥有的:


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


使用最后一行,它当前正在我所在的目录中写入文件,我希望它直接写入目标目录,任何想法如何继续?sperebin.write(spect_name + "-" + "rebin" + ".fits")


aluckdog
浏览 80回答 2
2回答

喵喔喔

使用 os.path.join,您可以将目录与文件名组合在一起以获取文件路径。sperebin.write(os.path.join(destination, pect_name + "-" + "rebin" + ".fits"))此外,使用os,您可以检查目录是否存在,并根据需要创建它。if not os.path.exists(destination):     os.makedirs(destination)

慕姐8265434

您不需要或不想更改脚本中的目录。相反,请使用路径库来简化新文件名的创建。from pathlib import Pathroot_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 objectfor 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))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python