循环遍历python中的文件名

时间:2012-06-11 19:07:35

标签: python

我想在运行脚本的目录中有多个文件。它们都有一个文件名,如:prefix_foo_123456_asdf_asdfasdf.csv。我知道如何使用shell中文件名中的变量而不是python来循环目录中的文件。是否有相应的方法来做

之类的事情
$i=0

for $i<100

./process.py prefix_foo_$i_*

$i++

endloop

3 个答案:

答案 0 :(得分:4)

您可以使用glob.globglob.iglob来获取文件名的列表/迭代器。

e.g。如果您的目录有“file1.txt”,“file2.txt”,“file3.txt”

import glob
print (glob.glob('*.txt'))  #['file1.txt','file2.txt','file3.txt']

虽然列表不一定要排序。

你的循环可以写成:

import subprocess
import glob
for i in range(100):
    files=glob.glob('prefix_foo_%d_*'%(i))
    subprocess.call(['./process.py']+files)

当然,在python中使用subprocess来运行另一个python程序可能不是最好的设计...(你可以从其他模块导入你需要的东西并运行它而不会产生另一个进程)

答案 1 :(得分:2)

使用标准库glob。假设process.py的功能在函数process_one_file中:

from glob import glob
from process import process_one_file

for i in range(100):
    process_one_file(glob('prefix_foo_{}_*'.format(i)))

答案 2 :(得分:2)

另一种方式:

from os import walk

>>> for filename, subdirs, dirs in walk('/home'):
...     print (filename, subdirs, dirs)

输出:

  

home / di / workspace / local2stream / mediaelement / .git / info [] ['exclude']   /home/di/workspace/local2stream/mediaelement/.git/logs ['refs']   ['HEAD'] /home/di/workspace/local2stream/mediaelement/.git/logs/refs   ['遥控','头'] []   /home/di/workspace/local2stream/mediaelement/.git/logs/refs/remotes   ['origin'] []   /home/di/workspace/local2stream/mediaelement/.git/logs/refs/remotes/origin   [] ['HEAD']   /home/di/workspace/local2stream/mediaelement/.git/logs/refs/heads []   ['master'] /home/di/workspace/local2stream/mediaelement/.git/objects   ['info','pack'] []   /home/di/workspace/local2stream/mediaelement/.git/objects/info [] []   /home/di/workspace/local2stream/mediaelement/.git/objects/pack []   [ '包-a378eaa927a4825f049faf10bab35cf5d94545f1.idx',   '包-a378eaa927a4825f049faf10bab35cf5d94545f1.pack']   /home/di/workspace/local2stream/mediaelement/.git/refs ['tags',   '遥控','头'] []   /home/di/workspace/local2stream/mediaelement/.git/refs/tags [] []   /home/di/workspace/local2stream/mediaelement/.git/refs/remotes   ['origin'] []   /home/di/workspace/local2stream/mediaelement/.git/refs/remotes/origin   [] ['HEAD']   /home/di/workspace/local2stream/mediaelement/.git/refs/heads []   [ '主']