我有一个Python脚本(我们称之为myscript.py
),我想应用于嵌套目录结构中的一堆文件。我将在集群环境中并行运行该脚本的调用,因此我想为此编写一个简短的bash脚本。在
因此给定一对文件,如xyz_1.gz
和xyz_2.gz
,它们嵌套在如下文件夹中:
A > ... > C1 > xyz_1.gz
A > ... > C1 > xyz_2.gz
A > ... > C1 > bunch of other files
A > ... > C2 > xyy_1.gz
A > ... > C2 > xyy_2.gz
A > ... > C2 > bunch of other files
A > ... > C3 > zzz_1.gz
A > ... > C3 > zzz_2.gz
A > ... > C3 > bunch of other files
A > B > some other things
这是一个愚蠢的例子,但我希望它至少传达了结构。在
我希望能够迭代目录结构并调用我的脚本:
^{pr2}$这样,输出文件就会在相应的文件夹中结束。在
到目前为止,我看到的大多数递归解决方案都对每个单独的文件使用find
或{
有什么建议吗?在
编辑:从我目前得到的答案来看,我想澄清一下,我事先并不知道以下三个参数:
(回答编辑后的问题。)
在shell中实现这一点比较困难(可读性较差),因此我求助于Python:
(为糟糕的Python风格感到抱歉:我实际上是一个Perl程序员。)
不要迭代文件-遍历目录。shell中的示例:
^{pr2}$或者,您仍然可以迭代文件,让
find
为我们检查其中一个文件。然后从找到的文件名中提取目录:此外,您还可以将开头的
cd $DIR
(os.chdir()
);将目录作为参数或env var传递到Python脚本本身,并检查输入文件(例如,如果文件不存在,则自动退出)。在下面是执行以下操作的bash脚本:
脚本在递归性方面非常严格,但我根据您的目录结构应用了它
不知道具体有多少文件,但类似的东西可以为您工作:
^{pr2}$我已经创建了一个虚拟的python脚本,它写出作为参数提供给它的文件名。这是python脚本:
相关问题 更多 >
编程相关推荐