sys.path.insert(0,dir)
python中,import module 会去 sys.path 中搜索,sys.path是个列表,并且我们可以动态修改。
要import某个目录的module,我们用 sys.path.insert(0,somedir) 来加入搜索路径,而且该路径是插入到path列表的最前面(这一点和sys.path.append(0,dir)不同),然后就可以import 路径中的module了。
同样这样,要import上一级目录的module,可以sys.path.insert(0,parentdir)。
glob
python 标准库中的glob模块用来查找文件目录和文件,并将搜索的到的结果返回到一个列表中,用遍历整个目录判断每个文件是不是符合.
常见的两个方法有glob.glob()和glob.iglob(),可以和常用的find功能进行类比,glob支持*?[]这三种通配符。
三种通配符
*代表0个或多个字符
?代表一个字符
[]匹配指定范围内的字符,如[0-9]匹配数字
glob.glob(pathname, *, root_dir=None, dir_fd=None, recursive=False)
# pathname:路径名可以是绝对的 或相对的,并且可以包含 shell 样式的通配符.
# 如果recursive为 true,则模式 "**" 将匹配任何文件以及零个或多个目录、子目录和指向目录的符号链接。
>>> import glob
>>> glob.glob('./[0-9].*')
['./1.gif', './2.txt']
>>> glob.glob('*.gif')
['1.gif', 'card.gif']
>>> glob.glob('?.gif')
['1.gif']
>>> glob.glob('**/*.txt', recursive=True)
['2.txt', 'sub/3.txt']
>>> glob.glob('./**/', recursive=True)
['./', './sub/']
np.where()
numpy.where(condition, [x, y, ]/)
Return elements chosen from x or y depending on condition.
Note
When only condition is provided, this function is a shorthand for np.asarray(condition).nonzero(). Using nonzero directly should be preferred, as it behaves correctly for subclasses. The rest of this documentation covers only the case where all three arguments are provided.
Parameters
-
condition :array_like, bool
Where True, yield x, otherwise yield y. -
x, y :array_like
Values from which to choose. x, y and condition need to be broadcastable to some shape.
Returns
- out:ndarray
An array with elements from x where condition is True, and elements from y elsewhere.1
np.asarray()
numpy.asarray(a, dtype=None, order=None, *, like=None)
Convert the input to an array.
Parameters:
-
a : array_like
Input data, in any form that can be converted to an array. This includes lists, lists of tuples, tuples, tuples of tuples, tuples of lists and ndarrays. -
dtype :data-type, optional
By default, the data-type is inferred from the input data. -
order{‘C’, ‘F’, ‘A’, ‘K’}, optional
Memory layout. ‘A’ and ‘K’ depend on the order of input array a. ‘C’ row-major (C-style), ‘F’ column-major (Fortran-style) memory representation. ‘A’ (any) means ‘F’ if a is Fortran contiguous, ‘C’ otherwise ‘K’ (keep) preserve input order Defaults to ‘K’. -
like :array_like
Reference object to allow the creation of arrays which are not NumPy arrays. If an array-like passed in as like supports the array_function protocol, the result will be defined by it. In this case, it ensures the creation of an array object compatible with that passed in via this argument.
Returns:
- out :ndarray
Array interpretation of a. No copy is performed if the input is already an ndarray with matching dtype and order. If a is a subclass of ndarray, a base class ndarray is returned.2