如何定义脚本加载文件的位置?

时间:2015-04-14 11:30:40

标签: python python-2.7 tkinter

我使用脚本的一部分从已注册的文件.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 个答案:

答案 0 :(得分: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))
    ...