处理目录中的所有文件 - 不同类型

时间:2016-02-25 18:31:20

标签: python python-3.x

所以我现在正在尝试编写代码来运行我刚刚创建的函数的目录中的每个文件。问题是,目录中的文件将有三种类型(.wav,.txt,以及程序的输出,.TextGrid),并且需要在代码中作为参数传入。因此,例如,特定的.wav文件必须使用它的特定.txt文件,以生成特定名称的.TextGrid文件。这些文件是我通过实际运行另一个程序的子进程传递的参数,Penn State中的Forced Aligner。如果您对任何代码或其功能感到困惑,请告诉我。

此外,我是编码的新手,所以我知道我的代码可能不是最有效的。我觉得使用输入而不是argv对于这个实例会更容易,主要是因为我不知道如何指定每次可能有不同数量的参数(我试图使这个代码更通用,但是我的目的,每次只有1个程序和3个参数。

import subprocess
import sys

def run_file(num_args):
    prog = input('Enter the program directory: ')
    args = input('Enter the arguments\' directories separated by a space: ').split(' ', len(num_args)-1)
    subprocess.call([prog, args])

def main():
    run_file(sys.argv)


if __name__ == '__main__':
    main()

1 个答案:

答案 0 :(得分:0)

您可以使用glob获取具有特定后缀的所有文件的列表,例如所有.txt文件。然后,您可以检查是否存在匹配的.wav文件,然后传递给对齐器。

import glob
import subprocess
import os

def main():
    # specify program
    prog = input('Enter the program directory: ')
    # no program is given, use a default program
    if not prog:
        prog = "./align.py"

    # compile a list of all .txt files in the current directory
    # using glob wildcards
    all_txt_files = glob.glob("*.txt")

    for txt_file in all_txt_files:
        # get the basename of the txt file, triming off the extension
        filename, ext = os.path.splitext(txt_file)
        # compile filenames for wav and textgrid file
        wav_file = filename + ".wav"
        grid_file = filename + ".TextGrid"
        # make sure the wav file exists
        if os.path.exists(wav_file):
            # call the program
            args = [txt_file, wav_file, grid_file]
            subprocess.Popen([prog] + args)


if __name__ == '__main__':
    main()

我不是100%确定这是你要做的。如果您想允许不同的参数,请考虑使用用户输入或命令行参数创建常量字符串。我没有测试过这个,但它可能看起来像这样:

    input_suffixes = input('Enter input suffixes\' separated by spaces').split(" ")
    if not input_suffixes:
        input_suffixes = ".txt .wav"

    output_suffixes = input('Enter output suffixes\' separated by spaces').split(" ")
    if not output_suffixes:
        output_suffixes = ".TextGrid"

    first_suffix, *input_suffixes = input_suffixes    
    all_files = glob.glob("*"+first_suffix)

    for in_file in all_txt_files:
        filename, ext = os.path.splitext(txt_file)
        in_files = [filename+suffix for suffix in input_suffixes]
        out_files = [filename+suffix for suffix in output_suffixes]

        args = [in_file] + in_files + out_files
        subprocess.Popen([prog] + args)

旁注

如果你使用的是linux机器,那么编写一个bash脚本来解决这个问题可能会更简单(或者更短):

for f in *.txt; do
  python align.py $f `basename $f .txt`.wav `basename $f .txt`.TextGrid;
done

这将遍历所有.txt文件,将文件名传递给align.py。其他文件的文件名是使用basename命令basename $f .txt创建的,该命令会修剪文件中的后缀。然后添加.wav和.TextGrid后缀。

我希望这会有所帮助,尽管实验室肯定是长期的。