Используя Python для выполнения команды на каждом файле в папке

Стандартный ML (34 символа и скучный):

fun p s=s=implode(rev(explode(s)))
51
задан Manu 15 July 2009 в 07:30
поделиться

6 ответов

To find all the filenames use os.listdir().

Then you loop over the filenames. Like so:

import os
for filename in os.listdir('dirname'):
     callthecommandhere(blablahbla, filename, foo)

If you prefer subprocess, use subprocess. :-)

106
ответ дан 7 November 2019 в 09:48
поделиться

Use os.walk to iterate recursively over directory content:

import os

root_dir = '.'

for directory, subdirectories, files in os.walk(root_dir):
    for file in files:
        print os.path.join(directory, file)

No real difference between os.system and subprocess.call here - unless you have to deal with strangely named files (filenames including spaces, quotation marks and so on). If this is the case, subprocess.call is definitely better, because you don't need to do any shell-quoting on file names. os.system is better when you need to accept any valid shell command, e.g. received from user in the configuration file.

25
ответ дан 7 November 2019 в 09:48
поделиться

AVI to MPG (pick your extensions):

files = os.listdir('/input')
for sourceVideo in files:
    if sourceVideo[-4:] != ".avi"
        continue
    destinationVideo = sourceVideo[:-4] + ".mpg"
    cmdLine = ['mencoder', sourceVideo, '-ovc', 'copy', '-oac', 'copy', '-ss',
        '00:02:54', '-endpos', '00:00:54', '-o', destinationVideo]
    output1 = Popen(cmdLine, stdout=PIPE).communicate()[0]
    print output1
    output2 = Popen(['del', sourceVideo], stdout=PIPE).communicate()[0]
    print output2
3
ответ дан 7 November 2019 в 09:48
поделиться

Python может оказаться излишним для этого.

for file in *; do mencoder -some options $file; rm -f $file ; done
11
ответ дан 7 November 2019 в 09:48
поделиться

Или вы можете использовать функцию os.path.walk, которая выполняет для вас больше работы, чем просто os.walk:

Глупый пример:

def walk_func(blah_args, dirname,names):
    print ' '.join(('In ',dirname,', called with ',blah_args))
    for name in names:
        print 'Walked on ' + name

if __name__ == '__main__':
    import os.path
    directory = './'
    arguments = '[args go here]'
    os.path.walk(directory,walk_func,arguments)
1
ответ дан 7 November 2019 в 09:48
поделиться

У меня была похожая проблема, с большой помощью из Интернета и этого сообщения я сделал небольшое приложение, моя цель - VCD и SVCD, и я не удаляю источник, но я думаю, что это будет довольно легко адаптировать к вашим собственным потребностям.

Он может конвертировать 1 видео и вырезать его или может конвертировать все видео в папке, переименовывать их и помещать в подпапку /VCD

Я также добавляю небольшой интерфейс, надеюсь, кому-то он покажется полезным!

Кстати, я разместил код и файл здесь: http://tequilaphp.wordpress.com/2010/08/27/learning-python-making-a-svcd-gui/

1
ответ дан 7 November 2019 в 09:48
поделиться
Другие вопросы по тегам:

Похожие вопросы: