일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 | 30 |
Tags
- 바운새
- 젖비단그물버섯
- 토양미생물학
- 대학원생
- 곤줄박이
- 영화 일기
- 코딩
- mushroom #mushrooms #mushroomhunting #mushroomphotos #mushroomphotography #mycology #mycologist #fungi #fungalecology #fungaldiversity #fantasticfungi #버섯 #탐균 #버섯탐사
- 토양학
- 계묘년
- 둠칫새
- 생물정보학
- RStudio
- 외생균근균
- 영화 해석
- 갓생
- 파이썬
- 청도요
- 영화 리뷰
- 에리히 프롬
- R
- 영화 후기
- 탐조
- 생명과학 균학 미생물학 Biology Mycology Microbiology
- Rstuido
- 더 웨일
- Cannon PowerShot G7 X Mark III
- 심리학
- 철학
- 영화
Archives
- Today
- Total
워라밸 중독자
[Python] 특정 문자열 목록을 포함하는 모든 파일 찾아서 복사하기 본문
아래 코드를 이용해 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 에 저장되었습니다.
'코딩, 딱 지금이 시작할때! (코딱지)' 카테고리의 다른 글
sudo 권한 없을 때 conda env에 make로 설치 (0) | 2023.07.17 |
---|---|
[R] 데이터 전처리 - 열 또는 행 이름 확인 및 변경하기 (0) | 2023.01.19 |
[Python] 사진 및 영상 배경 쉽게 제거해주는 프로그램 (무료, 여러개 한번에) (0) | 2023.01.12 |
[R] 사용자 설치 패키지 모두 삭제 (0) | 2023.01.12 |
[R] 인덱싱(indexing) - 데이터에서 원하는 값 추출 (1) | 2023.01.12 |