遍历文件夹并在python中一次访问两个文件

时间:2019-02-04 17:15:38

标签: python

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

void imLabel::draw(const QPoint &endPoint){
     QPainter painter(&image);
     painter.setPen(QPen(myPenColor, myPenWidth, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));
     if(tipo == "maoLivre" || tipo == "reta") //draw line or free hand
         painter.drawLine(startPoint, endPoint);
     else{
        int x = startPoint.x(), y = startPoint.y(),
        largura = endPoint.x()- startPoint.x(),
        altura = endPoint.y() - startPoint.y();
        if(tipo == "retangulo") //draw rectangle
             painter.fillRect(x,y,largura,altura,Qt::green);
        else if(tipo == "circulo"){ //draw circle
             painter.setBrush(Qt::green);
             painter.drawEllipse(startPoint,altura,altura);
        }
    }
    modified = true;
    update();
    startPoint = endPoint;
}

    k_0_1.m 
    k_0_2.m
    k_0_40.m 

目标是始终访问两个对应的文件,即

k_0_1.m,eq_0_1.txt

我开始遍历第一种文件,但是如何访问其他文件。目的是在每个文件中都有对应的矩阵。

    eq_0_1.txt
    eq_0_2.txt
    eq_0_40.txt

1 个答案:

答案 0 :(得分: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