使用 Python 对文件夹中的每个文件执行命令 [英] Using Python to execute a command on every file in a folder

查看:24
本文介绍了使用 Python 对文件夹中的每个文件执行命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个 Python 脚本:

I'm trying to create a Python script that would :

  1. 查看文件夹/input"
  2. 对于该文件夹中的每个视频,运行 mencoder 命令(将它们转码为可在我的手机上播放的内容)
  3. 在 mencoder 完成运行后,删除原始视频.

这似乎不太难,但我很擅长 python :)

That doesn't seem too hard, but I suck at python :)

关于脚本应该是什么样子的任何想法?

Any ideas on what the script should look like ?

奖励问题:我应该使用

操作系统

子进程调用

?

Subprocess.call 似乎允许使用更具可读性的脚本,因为我可以像这样编写命令:

Subprocess.call seems to allow for a more readable script, since I can write the command like this :

cmdLine = ['mencoder',源视频,'-ovc','复制','-oac','复制','-ss','00:02:54','-endpos','00:00:54','-o',目的地视频]

cmdLine = ['mencoder', sourceVideo, '-ovc', 'copy', '-oac', 'copy', '-ss', '00:02:54', '-endpos', '00:00:54', '-o', destinationVideo]

好的,那行得通:

import os, subprocess

bitrate = '100'
mencoder = 'C:\Program Files\_utilitaires\MPlayer-1.0rc2\mencoder.exe'
inputdir = 'C:\Documents and Settings\Administrator\Desktop\input'
outputdir = 'C:\Documents and Settings\Administrator\Desktop\output'

for fichier in os.listdir(inputdir):
    print 'fichier :' + fichier
    sourceVideo = inputdir + '\' + fichier
    destinationVideo = outputdir + '\' + fichier[:-4] + ".mp4"

    commande = [mencoder,
               '-of',
               'lavf',
               [...]
               '-mc',
               '0',

               sourceVideo,
               '-o',
               destinationVideo]

    subprocess.call(commande)

os.remove(sourceVideo)
raw_input('Press Enter to exit')

为了清晰起见,我已经删除了 mencoder 命令,因为我仍在研究它.

I've removed the mencoder command, for clarity and because I'm still working on it.

感谢大家的投入.

推荐答案

要查找所有文件名,请使用 os.listdir().

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. :-)

这篇关于使用 Python 对文件夹中的每个文件执行命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆