David
David

Reputation: 1267

Iterating files in directory by name

Ok, I have a directory with many files and subdirectories; among these ones there are 20 directories called mbr001, mbr002, ... until mbr020 that are the ones I am interested in.

I want to write a program that iteratively goes into mbr001, do somethings, then to mbr002, do the same things, and so on.

A solution with Python's os.chdir('./mbr001') until 20 seems pretty inefficient.

Besides, when I am in such directories, let's say for example mbr012, I want to create a variable that has in its name the number of the mbr where I am, in this case 12. Something like variable = 'mbr012_file.dat'. (This variable is used in what I am doing inside each directory, not relevant here).

What I would need would be something like this (note this is pseudo-code):

for i in mbr[i]:
    variable = "mbr[i]_file.dat"
    ...

How can I do the loop and the variable naming? Thanks in advance.

Upvotes: 0

Views: 92

Answers (4)

Vlad Bezden
Vlad Bezden

Reputation: 89527

In python 3.4 and above you can use pathlib and in python 3.6 and above you can use "f string" to format text

from pathlib import Path

for path in [d for d in Path.cwd().iterdir() if d.match("mbr*")]:
    variable = f"{path.name}_file.dat"
    # do other stuff

Upvotes: 1

Skycc
Skycc

Reputation: 3555

You just need to concatenate '_files.dat' into the directory name

import re
for i in mbr_list:
    variable = i + '_files.dat'
    # use regex if you only interest on the numeric part
    # variable = re.sub('mbr(\d+)', r'mbr\1_file.dat', i)
    # do your thing here

Upvotes: 1

C.LECLERC
C.LECLERC

Reputation: 510

What about something like this ?

for i in range(1, 21):
    dn =  "./mbr{:03}".format(i)
    var = "mbr{:03}_file.dat".format(i)
    os.chdir(dn)
    # Do your stuff here
    #
    #
    os.chdir("..")

Upvotes: 1

user6999902
user6999902

Reputation:

Use format:

for i in list_of_is:
    filename = "mbr{0:02d}_file.dat".format(i)

Upvotes: 1

Related Questions