亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

將創建的文件保存到循環中的新目錄中

將創建的文件保存到循環中的新目錄中

aluckdog 2022-09-27 09:56:05
我目前正在使用循環更新目錄中的一些文件,我想將這些文件保存在其他目錄中。這是我所擁有的: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)


查看完整回答
反對 回復 2022-09-27
?
慕姐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))


查看完整回答
反對 回復 2022-09-27
  • 2 回答
  • 0 關注
  • 98 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號