我目前正在使用循環更新目錄中的一些文件,我想將這些文件保存在其他目錄中。這是我所擁有的:from astropy.io import fitsfrom mpdaf.obj import Spectrum, WaveCoordimport os, globROOT_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")
2 回答

喵喔喔
TA貢獻1735條經驗 獲得超5個贊
使用 os.path.join,您可以將目錄與文件名組合在一起以獲取文件路徑。
sperebin.write(os.path.join(destination, pect_name + "-" + "rebin" + ".fits"))
此外,使用os,您可以檢查目錄是否存在,并根據需要創建它。
if not os.path.exists(destination): os.makedirs(destination)

慕姐8265434
TA貢獻1813條經驗 獲得超2個贊
您不需要或不想更改腳本中的目錄。相反,請使用路徑庫來簡化新文件名的創建。
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))
添加回答
舉報
0/150
提交
取消