分别在目录中的特定文件上运行代码(按文件名)

时间:2018-08-06 15:03:22

标签: python-3.x loops import filenames nested-loops

我在同一文件夹中有N个文件,它们的索引号如

Fe_1Sec_1_.txt
Fe_1Sec_2_.txt
Fe_1Sec_3_.txt

Fe_2Sec_1_.txt
Fe_2Sec_2_.txt
Fe_2Sec_3_.txt
.
.
.
and so on

例如:如果我只需要运行时间等于1秒的文件来运行我的代码,则可以按照以下步骤手动进行设置:

path = "input/*_1Sec_*.txt"
files = glob.glob(path)
print(files)

这给了我

Out[103]: ['input\\Fe_1Sec_1_.txt', 'input\\Fe_1Sec_2_.txt', 'input\\Fe_1Sec_3_.txt']

如果需要为所有文件分别运行我的代码(取决于以秒为单位的测量时间,即文件名)
我尝试使用此代码来获取每次测量的路径:

time = 0
while time < 4:
   time += 1
   t = str(time)
   path = ('"input/*_'+t+'Sec_*.txt"')

这给了我

"input/*_1Sec_*.txt"
"input/*_2Sec_*.txt"
"input/*_3Sec_*.txt"
"input/*_4Sec_*.txt"

之后,我尝试使用此路径,如下所示:

files = glob.glob(path)
print(files)

但是它不会导入想要的文件并给我:

 "input/*_1Sec_*.txt"
 []
 "input/*_2Sec_*.txt"
 []
 "input/*_3Sec_*.txt"
 []
 "input/*_4Sec_*.txt"
 []

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

我认为最好的方法就是简单地做

import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JPanel; 

public class Screen extends JPanel{
private static final long serialVersionUID = 1L;
private static BufferedImage image;
private int x, y, w, h;

public Screen() {
    repaint();
}
Graphics graphics;
public void paintComponent(Graphics g) {
    graphics = g;
}

public void rect(int x, int y, int width, int height) {
    graphics.fillOval(x, y, width, height);
}

public void ellipse(int x, int y, int width, int height) {          
    graphics.fillOval(x, y, width, height);
}

public void fill(int red, int gr, int bl) {
    graphics.setColor(new Color(red, gr, bl));
}

public void fill1(int gs) {
    graphics.setColor(new Color(gs,gs,gs));
}

public void background(int red, int gr, int bl) {
    Color c = graphics.getColor();
    graphics.setColor(new Color(red, gr, bl));
    graphics.fillRect(0, 0, SnakeGame.gameSizeX, SnakeGame.gameSizeY);
    graphics.setColor(c);
}

public void background(int gs) {
    Color c = graphics.getColor();
    graphics.setColor(new Color(gs, gs, gs));
    graphics.fillRect(0, 0, SnakeGame.gameSizeX, SnakeGame.gameSizeY);
    graphics.setColor(c);
}

public void text(String text, int x, int y) {
    graphics.drawString(text, x, y);
}

public BufferedImage loadImage(String img) {
    try {
        image = ImageIO.read(getClass().getResourceAsStream("/" + img));
    } catch (IOException e) {
        e.printStackTrace();
    }
    return image;   
}

public void image(BufferedImage image, int x, int y, int w, int h) {

    graphics.drawImage(image, x, y, w, h, null);
}

}