1

スクリプトを実行したいディレクトリに無数のファイルがあります。それらはすべて、prefix_foo_123456_asdf_asdfasdf.csv のようなファイル名を持っています。シェルのファイル名の変数を使用してディレクトリ内のファイルをループする方法は知っていますが、Python は知りません。次のようなことを行う対応する方法はありますか

$i=0

for $i<100

./process.py prefix_foo_$i_*

$i++

endloop
4

3 に答える 3

4

glob.globまたはを使用glob.iglobして、ファイル名のリスト/イテレータを取得できます。

たとえば、ディレクトリに「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 でサブプロセスを使用して別の python プログラムを実行することは、おそらく最適な設計ではありません... (おそらく、必要なものを他のモジュールからインポートして、別のプロセスを生成せずに実行することができます)

于 2012-06-11T19:09:55.833 に答える
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)))
于 2012-06-11T19:15:24.600 に答える
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 ['remotes', 'heads'] [] /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 [] [ 'マスター'] /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 [] ['pack-a378eaa927a4825f049faf10bab35cf5d94545f1.idx','pack-a378eaa927a4825f049faf10bab35cf5d94545f1.pack'] /home/di/workspace/local2stream/mediaelement/.git/refs ['tags', 'remotes', 'heads'] [] /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 [] ['master']] [] /home/di/workspace/local2stream/mediaelement/.git/refs/remotes/origin [] ['HEAD'] /home/di/workspace/local2stream/mediaelement/.git/refs/heads [] ['主人']] [] /home/di/workspace/local2stream/mediaelement/.git/refs/remotes/origin [] ['HEAD'] /home/di/workspace/local2stream/mediaelement/.git/refs/heads [] ['主人']

于 2012-06-11T19:19:21.307 に答える