lovespeed
lovespeed

Reputation: 5045

Extract number from file name in python

I have a directory where I have many data files, but the data file names have arbitrary numbers. For example

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

and so on. Because of the decimals in the file names they are not sorted according to the value of the numbers. What I want to do is the following: I want to open every file, extract the number from the file name, put it in a array and do some manipulations using the data. Example:

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

I want to do this for every file by running a loop. I think it could be done by creating an array containing all the file names (using import os) and then doing something with it. How can it be done?

Upvotes: 0

Views: 6744

Answers (2)

Roman  Fursenko
Roman Fursenko

Reputation: 688

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()

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1121834

If your files all start with the same prefix and end with the same suffix, simply slice and pass to float():

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

This removes the first 7 characters (i.e. data_T_) and the last 2 (.d).

This works fine for your example filenames:

>>> 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

Upvotes: 8

Related Questions