gpt4 book ai didi

python - 递归地导航文件系统以分析成对的文件

转载 作者:太空宇宙 更新时间:2023-11-03 16:47:15 26 4
gpt4 key购买 nike

我有一个 Python 脚本(我们称之为 myscript.py),我想应用于嵌套目录结构中的一堆文件。我将在集群环境中并行运行此脚本的调用,因此我想为此编写一个简短的 bash 脚本。

因此,给定像 xyz_1.gzxyz_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

上面是一个愚蠢的例子,但我希望它至少传达了结构。

我希望能够迭代目录结构并调用我的脚本:

myscript.py xyz_1.gz xyz_2.gz outputfile

这样输出文件最终会出现在相应的文件夹中。

到目前为止,我见过的大多数递归解决方案都使用 findgrep 来查找每个单独的文件,但是我也需要位置,以便将它们配对并写入磁盘到适当的地方。

有什么建议吗?

编辑:从我到目前为止得到的答案来看,我想澄清一下,我事先并不知道以下三个参数:

  1. 保存 .gz 文件的子目录的深度,即我不知道之间存在多少个中间目录
  2. 子目录的名称
  3. 文件的名称,除了 _1/_2 后缀之外,它们都相同

最佳答案

(回答已编辑的问题。)

在 shell 中完成有点困难(可读性较差),因此我求助于 Python:

#!/usr/bin/env python3
import os
import re
import pprint
from sets import Set
from subprocess import call

group1 = {} # collect here the filenames for _1
group2 = {} # collect here the filenames for _2

for root, directories, filenames in os.walk('.'):
for filename in filenames:
ff = os.path.join(root,filename)
if filename.endswith("_1.txt"):
base = re.sub('_1\.txt$','', ff)
group1[base] = ff
if filename.endswith("_2.txt"):
base = re.sub('_2\.txt$','', ff)
group2[base] = ff

#pprint.pprint(group1)
#pprint.pprint(group2)

# find common ones: the dirs which contain the files with the common prefix:
list1 = Set(group1.keys()).intersection(Set(group2.keys()))

#pprint.pprint(list1)

# call the myscript.py
cwd = os.getcwd()
for base in list1:
path, filename = os.path.split(base)
#print path," ",filename
try:
os.chdir(path)
call(['echo', 'myscript.py', filename+"_1.txt", filename+"_2.txt", "outputfile"])
finally:
os.chdir(cwd)

(对蹩脚的 Python 风格感到抱歉:我实际上是一名 Perl 程序员。)

<小时/>

Most recursive solutions I have seen so far use either find or grep for each individual file however I need the location as well, to get them in pairs and write to disk at the appropriate place.

不要迭代文件 - 迭代目录。 shell 中的示例:

find -type d -print |
while read DIR; do
test -r $DIR/xyz_1.gz -a -r $DIR/xyz_2.gz -a -r $DIR/some_other_file || continue
( cd $DIR; myscript.py xyz_1.gz xyz_2.gz outputfile )
done

或者,您仍然可以迭代文件,让 find 为我们检查其中一个文件。然后从找到的文件名中提取目录:

find -type f -name xyz_1.gz -print |
while read FN; do
DIR=`dirname $FN`
test -r $DIR/xyz_2.gz -a -r $DIR/some_other_file || continue
( cd $DIR; myscript.py xyz_1.gz xyz_2.gz outputfile )
done

此外,您可以将 cd $DIR (os.chdir() 放在开头;将目录作为参数或环境变量传递)到 Python 中脚本本身,以及对输入文件的检查(例如,如果文件不存在,则静默退出)。

关于python - 递归地导航文件系统以分析成对的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36198401/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com