【问题标题】:Loop through many files in 2 directories循环遍历 2 个目录中的许多文件
【发布时间】:2022-10-04 16:38:16
【问题描述】:

给定:带有 A.txt 和 B.txt 的文件夹 1 和带有 A.txt 的文件夹 2。和 B.txt
我如何能够同时运行它们,例如文件夹 1 中的文件 A.txt 应该与文件夹 2 A.txt 中的文件一起运行等等。
到目前为止,我所拥有的内容会遍历所有第二个文件夹文件,然后遍历第一个文件夹文件,这会使其无序。将完成一些事情,例如将部分文件合并在一起(到目前为止已经完成)。
我的主要问题是如何同时运行 2 个目录并在其中执行操作。
请注意,文件夹 1 和文件夹 2 中有很多文件,所以我需要找到一种利用某种目录模式的方法
patha=/文件夹1
pathb=/文件夹2

import os,glob
for filename in glob.glob(os.path.join(patha,'*.txt'):
 for filenamez in glob.glob(os.path.join(pathb,'*.txt'):
     MY FUNCTION THAT DOES OTHER STUFF

【问题讨论】:

  • 是否保证两个文件夹中都存在名称匹配?如果文件夹 1 的文件名是不是在文件夹 2 中?

标签: python python-3.x


【解决方案1】:

您可以使用上下文管理器同时在两个文件夹中打开具有相同名称的文件,并从两个输入流中执行任何需要执行的操作:

import os

my_folders = ['Folder1', 'Folder2']

common_files = set(os.listdir('Folder1')) & set(os.listdir('Folder2'))
non_common_files = set(os.listdir('Folder1')) ^ set(os.listdir('Folder2'))

print(f'common_files" {common_files}')
print(f'files without matches: {non_common_files}')

for f_name in common_files:
    with open(os.path.join(my_folders[0], f_name)) as src_1:
        with open(os.path.join(my_folders[1], f_name)) as src_2:
            # do the stuff on both sources... for instance print first line of each:
            print(f'first line of src_1: {src_1.readline()}')
            print(f'first line of src_2: {src_2.readline()}')

输出

common_files" {'A.txt'}
files without matches: set()
first line of src_1: some txt

first line of src_2: text in folder 2's A

【讨论】:

    【解决方案2】:

    您的 for 循环是嵌套的,因此它不会是并发的。要同时运行它们,每个 for 循环都必须是分开的。

    【讨论】:

    【解决方案3】:

    zip 是你要找的吗?

    import glob
    import os
    
    files_a = glob.glob(os.path.join(path_a, "*.txt")
    files_b = glob.glob(os.path.join(path_b, "*.txt")
    for file_a, file_b in zip(files_a, files_b):
        pass
    

    【讨论】:

      【解决方案4】:

      你也许可以做这样的事情:

      from threading import Thread
      import os,glob
      
      def dir_iterate(path: str):
          for filename in glob.glob(os.path.join(path,'*.txt'):
              # Other stuff ..
      
      
      path1 = "./directory1"
      path2 = "./directory2"
      Thread(target = dir_iterate, args=(path1,)).start()
      Thread(target = dir_iterate, args=(path2,)).start()
      

      【讨论】:

      • OP 不清楚,但表示他们想“合并一些数据”等,这意味着线程在这种情况下不太可能独立
      【解决方案5】:

      这应该工作,

      import glob
      import os
      
      files_a = sorted(glob.glob(os.path.join(path_a, "*.txt")))
      files_b = sorted(glob.glob(os.path.join(path_b, "*.txt")))
      
      for file_a, file_b in zip(files_a, files_b):
          # Add code to concat
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-07-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多