How to read many files in a folder and selectively keep some files

Table of contents

Problem Description:

problem solved:


Problem Description:

There is currently a secondary folder. The folder name of the first level is "Papers(LNAI14302-14304)", and the directory name of the second level folder is shown in the blue part of the figure below. The third layer is the stored files, as shown in the figure below, each file contains three files, namely copyright.pdf, submission.pdf, source.zip.

How to implement it in python, read the contents of the files in the three-level directory, and filter and save the "submission.pdf" in the innermost directory.

 

problem solved:

Python realizes reading the content in the folder, and filtering some of the content, and writing it to another folder.

import os
import shutil

source_parent_folder = "Papers (LNAI14302-14305)"  # 主文件夹
target_parent_folder = "LANI_submission"  # 目标文件夹

# 确保目标文件夹存在
os.makedirs(target_parent_folder, exist_ok=True)

for folder_name in os.listdir(source_parent_folder):
    folder_path = os.path.join(source_parent_folder, folder_name)
    
    if os.path.isdir(folder_path):
        source_file_pth = os.path.join(folder_path, "submission.pdf")
        target_folder_path = os.path.join(target_parent_folder, folder_name)
        target_file_path = os.path.join(target_folder_path, "submission.pdf")
        # 确保目标子文件夹存在
        os.makedirs(target_folder_path, exist_ok=True)

        if os.path.exists(source_file_pth):
            shutil.copy2(source_file_pth, target_file_path) # shutil.copy2()不仅保存内容,也保存源文件的一切具体信息。比如格式等信息,不同于shutil.copy()
            print(f"Copied submission from {folder_name} to {target_folder_path}")


Guess you like

Origin blog.csdn.net/weixin_41862755/article/details/132267236