从python中的文件名中提取数字

时间:2013-03-14 18:55:55

标签: python file python-2.7 python-3.x file-handling

我有一个目录,我有很多数据文件,但数据文件名有任意数字。例如

data_T_1e-05.d
data_T_7.2434.d
data_T_0.001.d

等等。由于文件名中的小数,它们不会根据数字的值进行排序。我想做的是以下内容: 我想打开每个文件,从文件名中提取数字,将其放入数组中并使用数据进行一些操作。例如:

a = np.loadtxt("data_T_1e-05.d",unpack=True)
res[i][0] = 1e-05
res[i][1] = np.sum[a]

我想通过运行循环为每个文件执行此操作。我认为可以通过创建一个包含所有文件名的数组(使用import os)然后用它做一些事情来完成。 怎么办呢?

2 个答案:

答案 0 :(得分:8)

如果您的文件都以相同的前缀开头并以相同的后缀结尾,只需切片并传递给float()

number = float(filename[7:-2])

这会删除前7个字符(即data_T_)和最后2个字符(.d)。

这适用于您的示例文件名:

>>> for example in ('data_T_1e-05.d', 'data_T_7.2434.d', 'data_T_0.001.d'):
...     print float(example[7:-2])
... 
1e-05
7.2434
0.001

答案 1 :(得分:1)

import os
# create the list containing all files from the current dir
filelistall = os.listdir(os.getcwd())
# create the list containing only data files. 
# I assume that data file names end with ".d"
filelist = filter(lambda x: x.endswith('.d'), filelistall)
for filename in filelist:
   f = open(filename, "r")
   number = float(filename[7:-2])
   # and any other code dealing with file
   f.close()
相关问题