2015-04-14 90 views
1

我使用我的腳本的一部分從註冊文件加載數據.npz如何從腳本加載文件的位置進行定義?

Here is the code

Tk().withdraw() # Here starts the first loading phase, where I pick the file I want from a window 
filename = askopenfilename() 
with load(filename) as data: 
    # file loading logic here 
    pass 

ext = '.npz' 
for i in range(1, NF): # Here starts the second part, which loads one by one from the folder where the script is. 
    filename = str(i) + ext 
    with load(filename) as data: 
     XYsliceTemp = data['XYslice'] 

那麼,什麼是我的問題嗎?現在,當我處於所描述的第二階段時,它會從腳本所在的文件夾逐個加載文件。 我想以我可以選擇的方式對其進行編碼(通過打開窗口或通過在代碼中寫入完整地址的內容)來加載文件的位置(所有文件始終位於同一文件夾中)

這是背景:我要將我的數據存儲在一個不適合工作的硬盤上,所以我不能在其上安裝python並從中運行它。 所以我想告訴我的電腦上的腳本:去這些文件在硬盤上的確切位置。

實際上,第一階段加載文件0,然後第二階段從1加載到N。所以如果我可以說:我選擇加載0的地方,去那裏找到N個人,這將是完美的。

回答

1

使用os.path.split這樣的()os.path.join()方法

import os 

filename = askopenfilename() 
directory = os.path.split(filename)[0] 

ext = 'npz' 

for i in range(1, NF): 
    filename = os.path.join(directory, '%s.%s' % (i, ext)) 
    ... 
+0

謝謝!這似乎方便和容易。 我會盡快嘗試。 – Magea

相關問題