워라밸 중독자

[Python] 특정 문자열 목록을 포함하는 모든 파일 찾아서 복사하기 본문

코딩, 딱 지금이 시작할때! (코딱지)

[Python] 특정 문자열 목록을 포함하는 모든 파일 찾아서 복사하기

Ufungi 2023. 1. 17. 13:50

아래 코드를 이용해 strings.txt에 있는 문자열 목록을 포함하는 모든 파일을 찾아 다른 폴더로 복사할수 있습니다.

 

extension 변수를 통해 특정 확장자를 지정할 수도 있습니다.

 

strings.txt 에 포함되었으나 파일들에 없는 문자열은 not_matched_strings.txt 에 저장됩니다. 이를 통해 검색되지 않은 문자열이 무엇인지 tracking 할 수도 있습니다.

import os
import shutil

# list of strings to match in file names
with open('strings.txt', 'r') as f:
    strings = [line.strip() for line in f]

# extension of files to be copied
extension = '.txt'

# source and destination directories
src_dirs = ["path/to/source/folder1", "path/to/source/folder2", "path/to/source/folder3"]
dst_dir = "path/to/destination/folder"

#create a set to keep track of the matched strings
matched_strings = set()

# walk through each source folder and its subdirectories
for src_dir in src_dirs:
    for root, dirs, files in os.walk(src_dir):
        for file in files:
            # check if the file has the specified extension
            if file.endswith(extension):
                # check if the file name contains any of the strings in the list
                for string in strings:
                    if string in file:
                        # construct the full path to the file
                        src_path = os.path.join(root, file)
                        # construct the full path to the destination
                        dst_path = os.path.join(dst_dir, file)
                        # copy the file to the destination
                        shutil.copy(src_path, dst_path)
                        matched_strings.add(string)
                        break

#create a list of strings that did not match any file names
not_matched_strings = [string for string in strings if string not in matched_strings]

#write the not matched strings to a file
with open("not_matched_strings.txt", "w") as f:
    f.write("\n".join(not_matched_strings))

 

아래는 예시입니다.

 

다음과 같이 strings.txt 파일에 문자열 목록을 작성합니다.

 

import os
import shutil

# list of strings to match in file names
with open('strings.txt', 'r') as f:
    strings = [line.strip() for line in f]

# extension of files to be copied
extension = '.ab1'

# source and destination directories
src_dirs = ["E:/OneDrive - SNU/OneDrive - SNU/01_Project/태백산 자생발굴/",
            "E:/OneDrive - SNU/OneDrive - SNU/000_개인/00_블로그/코딱지/Python project/tmp/"]
dst_dir = "E:/OneDrive - SNU/OneDrive - SNU/000_개인/00_블로그/코딱지/Python project/AB1/"

#create a set to keep track of the matched strings
matched_strings = set()

# walk through each source folder and its subdirectories
for src_dir in src_dirs:
    for root, dirs, files in os.walk(src_dir):
        for file in files:
            # check if the file has the specified extension
            if file.endswith(extension):
                # check if the file name contains any of the strings in the list
                for string in strings:
                    if string in file:
                        # construct the full path to the file
                        src_path = os.path.join(root, file)
                        # construct the full path to the destination
                        dst_path = os.path.join(dst_dir, file)
                        # copy the file to the destination
                        shutil.copy(src_path, dst_path)
                        matched_strings.add(string)
                        break

#create a list of strings that did not match any file names
not_matched_strings = [string for string in strings if string not in matched_strings]

#write the not matched strings to a file
with open("not_matched_strings.txt", "w") as f:
    f.write("\n".join(not_matched_strings))

 

코드 실행 결과 strings.txt 파일에 적힌 문자열 목록을 포함하는 모든 파일이 대상 폴더로 복사되었습니다.

 

또한 찾지 못한 문자열 목록은 not_matched_strings.txt 에 저장되었습니다.