【问题标题】:Python iterate through subdirectories finding file pairsPython遍历子目录查找文件对
【发布时间】:2018-07-28 12:12:49
【问题描述】:

我有一个像这样的深层子文件夹结构:

a/b/file1.txt
a/b/file1.doc
a/b/file2.txt
a/b/file2.doc
a/c/file3.txt
a/c/file3.doc
a/c/d/file4.txt
a/c/d/file4.doc

我想提取所有的 .txt 和 .doc 文件对 - 例如到一个元组列表中 - 文件名相同,只是文件类型不同。

到目前为止,我想出的最好的是以下看起来效率不高的方法:

files = []
for root, dirs, files in os.walk(path):
    for filename in files:
        if os.path.isdir(os.path.join(os.path.abspath("."), filename)):
            file_list = os.listdir(filename)
            file_list_copy = file_list.copy()
            #for each in file_list of type .txt
            # find .doc of same name in file_list_copy
            #add the 2 to tuple nd append to list

【问题讨论】:

    标签: python path directory


    【解决方案1】:

    可能不是最有效但有效:

    使用 shell 命令将类型移动到单独的文件夹(为 txt 和 doc 扩展运行以创建 2 个文件夹):

    find /path-to-files-root/ -type f -name '*.txt' -exec mv -i {} /new-path-to-files/txt/ \;
    

    然后我跑了:

    def get_all_files(path, pattern):
    #see https://stackoverflow.com/questions/17282887/getting-files-with-same-name-irrespective-of-their-extension
        datafiles = []
        for root,dirs,files in os.walk(path):
            for file in fnmatch.filter(files, pattern):
                datafiles.append(file)
        return datafiles
    
    txt_files = [f for f in os.listdir(txt_path) if isfile(join(txt_path, f))]
    doc_files = [f for f in os.listdir(doc_path) if isfile(join(doc_path, f))]
    for i, txt_file in enumerate(txt_files):
        filename = (os.path.splitext(txt_file)[0])
        doc_files = get_all_files(doc_path, '{0}.doc'.format(filename))
        if len(doc_files)== 1:
            doc_file = doc_files[0]
            #do something with txt_file and doc_file
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-17
      • 1970-01-01
      • 2021-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-19
      • 1970-01-01
      相关资源
      最近更新 更多