如何使用Numpy的genfromtxt打开文件,但只指定目录路径的一部分?

huangapple go评论67阅读模式
英文:

How to open a file using Numpy's genfromtxt but specifying only part of the directory path?

问题

我想使用genfromtxt打开位于目录a/b/foldername_12345678中的文件。以下内容适用于我:

file = np.genfromtxt("a/b/foldername_12345678/filename")

但是,我不想追踪目录路径末尾的数字(它们与“foldername”唯一关联)。换句话说,我想在不指定完整目录路径的情况下打开文件。在Linux中,我可以通过以下方式实现:

cat a/b/foldername*/filename

如何在genfromtxt中实现相同的效果?

英文:

I would like to open a file located in the directory a/b/foldername_12345678 using genfromtxt. The following works for me

file = np.genfromtxt("a/b/foldername_12345678/filename")

However, I don't want to keep track of the numbers at the end of the directory path in which the file is located (they are uniquely associated with "foldername"). In other words, I would like to open the file without specifying the full directory path. In linux, I can do this via e.g.

cat a/b/foldername*/filename

How can I do the same with genfromtxt?

答案1

得分: 0

你可以在glob库中使用通配符。

import numpy as np
import glob

filepath = glob.glob("a/b/foldername*/filename")[0]
file = np.genfromtxt(filepath)

0索引假设只有一个可能的文件会使用这个通配符被找到。

英文:

You can use wildcards with the glob library.

import numpy as np
import glob

filepath = glob.glob("a/b/foldername*/filename")[0]
file = np.genfromtxt(filepath)

The 0 indexing assumes that there is only one possible file that will be found using this wildcard.

huangapple
  • 本文由 发表于 2023年7月13日 00:13:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/76672580.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定