user7503022
user7503022

Reputation:

Iterate through folder and access two files at once in python

I have a folder with two different types of files i.e.

    k_0_1.m 
    k_0_2.m
    k_0_40.m 

and

    eq_0_1.txt
    eq_0_2.txt
    eq_0_40.txt

The goal is to access always both files which are corresponding i.e.

k_0_1.m, eq_0_1.txt

I started to iterate over the first type of file but how do I access the other file. The goal is that in each file are matrices which are corresponding.

for file in os.listdir('directory'):
    filename = os.fsdecode(file)
    if filename.startswith('k_0_'):
       continue

Upvotes: 0

Views: 186

Answers (1)

r.ook
r.ook

Reputation: 13878

for file1 in os.listdir('directory'):
    if file1.endswith('.m') and file1.startswith('k_0_'):
        file2 = file1name.replace('k', 'eq').replace('.m', '.txt')

        with open(file1, 'r') as f1, open(file2, 'r') as f2:
            # ... do what you need with f1 and f2
            # change the mode from 'r' to the appropriate mode you require

Upvotes: 1

Related Questions