通过文件夹和迭代Python中同时访问两个文件

问题描述 投票:0回答:1

我有两个不同类型的文件,即一个文件夹

    k_0_1.m 
    k_0_2.m
    k_0_40.m 

    eq_0_1.txt
    eq_0_2.txt
    eq_0_40.txt

我们的目标是访问总是被相应的两个文件,即

k_0_1.m,eq_0_1.txt

我开始遍历第一类型的文件,但我怎么访问其他文件。的目标是,在每个文件都被对应的矩阵。

for file in os.listdir('directory'):
    filename = os.fsdecode(file)
    if filename.startswith('k_0_'):
       continue
python
1个回答
1
投票
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
© www.soinside.com 2019 - 2024. All rights reserved.