简体   繁体   English

制作Python脚本以加载目录中的所有npy / npz文件

[英]Making a Python script to load all npy/npz files in a directory

I want to load all npy/npz files into my interactive python shell, so I don't have to go: 我想将所有npy / npz文件加载到我的交互式python shell中,所以我不必去:

var1 = np.load('var1.npy')

for each one. 每一个人。 I made this script, but it doesn't work because it the variables namespace is just within the script (pretend the indenting is correct). 我制作了这个脚本,但它不起作用,因为变量命名空间就在脚本中(假装缩进是正确的)。 What is the right way to do this? 这样做的正确方法是什么?

def load_all():
import numpy as np
from os import listdir
from os.path import isfile, join
from os import getcwd

mypath = getcwd()
print 'loading all .npy and .npz files from ',mypath
files = [ f for f in listdir(mypath) if isfile(join(mypath,f)) ]

for f in files:  
    if f[-4:] in ('.npy','.npz'):
        name = f[:-4]+'_'+f[-3:]
        print 'loading', f, 'as', name
        var = np.load(f)
        exec(name + " = var")

I'd use glob . 我用的是glob For example, glob.glob('*.np[yz]') will return a list of all .npy and .npz filenames in the current directory. 例如, glob.glob('*.np[yz]')将返回当前目录中所有.npy和.npz文件名的列表。 You can then iterate over that list, loading each filename in turn. 然后,您可以遍历该列表,依次加载每个文件名。 Are you trying to then put the results of loading them into local variables that match the filename? 您是否尝试将加载它们的结果放入与文件名匹配的局部变量中? There are safer designs than that - I'd use a single dictionary and use the names as keys, something like: 有比这更安全的设计 - 我使用单个字典并使用名称作为键,如下所示:

numpy_vars = {}
for np_name in glob.glob('*.np[yz]'):
    numpy_vars[np_name] = np.load(np_name)

Simple and pythonic. 简单和pythonic。

import numpy as np
from os import listdir

directory_path = '.'
file_types = ['npy', 'npz']

np_vars = {dir_content: np.load(dir_content)
           for dir_content in listdir(directory_path)
           if dir_content.split('.')[-1] in file_types}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM