6일차 마무리

개발자 동찬 ㅣ 2023. 10. 17. 19:50

파일의 이름으로 파일을 검색하는 name_finder() 함수 구현

 

추상 자료형 정의

 

자료구조 때 학습한 ADT를 먼저 정의한 후 코드를 구현하여 보았다.

검색할 파일 이름 입력 :

if matching_files:
총 N개의 파일을 찾았습니다.

찾은 파일 디렉터리 : 
1번 파일 :
2번 파일 :
3번 파일 :

else:
찾는 파일이 없습니다.

 

# name_finder 구현한 코드

def name_finder():

  target_name = input("검색할 파일의 이름 입력 : ")
  target_name = target_name.strip()+".json" # 앞뒤 공백 제거
  files = [f for f in os.listdir('.') if os.path.isfile(f) and f.endswith('.json')] # 현재 폴더에 있는 모든 디렉터리에 있는 json 파일을 검색하여 리스트에 저장

  matching_files = []
  count = 0

  for file_target_name in files:
        with open(file_target_name, 'r') as file:
          if file_target_name == target_name:
            matching_files.append((file_target_name,file.dir()))
            count += 1

  if matching_files:
        print(f'총 {count}개의 파일을 찾았습니다.')
        print(f"'{target_name}'파일 목록: ")
        for i,matched_file in enumerate(matching_files,start=1):
          print(f'{i} : {matched_file}')

       
  else:
      print(f"'{target_name}' 이름의 파일이 없습니다.")

현재 하위 디렉터리까지 dfs를 하는 경우 까지 고려하여 중복 검색한 결과까지 처리하였지만,

 

현재 코드는 현재 디렉터리만 검색할 수 있다.

 

다음에는 좀더 발전하여 재귀를 이용한 DFS 를 이용하는 코드를 구현해보고 싶다,

 

#제출 소스코드 전체

import hashlib

import os
import json

def produce_file():
    file_target_name = input("파일명을 입력하세요 : ")
    tags_input = input("태그를 입력하세요 (띄어쓰기 구분): ")
    tags = [tag.strip() for tag in tags_input.split(' ')]
    file_content = input("파일에 저장할 내용을 입력 : ")

    file_data = {'content': file_content, 'tags': tags}
   
    with open(file_target_name + '.json', 'w',encoding='UTF8') as file:
        json.dump(file_data, file)

    print(f"파일 '{file_target_name}.txt'이(가) 생성되었습니다.")

# 파일의 해시값을 구하는 프로그램

def hash_find(filepath, blocksize=8192):
    sha_1 = hashlib.sha1()
    try:
        f = open(filepath, "rb")
    except IOError as e:
        print("file open error", e)
        return
    while True:
        buf = f.read(blocksize)
        if not buf:
            break
        sha_1.update(buf)
    return sha_1.hexdigest()

def content_finder():
  target_content = input("검색할 내용을 입력하세요 : ")
  target_content = target_content.strip()

  files = [f for f in os.listdir('.') if os.path.isfile(f) and f.endswith('.json')]

  matching_files = []
  count = 0

  for file_target_name in files:
        with open(file_target_name, 'r') as file:
            file_data = json.load(file)
            content = file_data.get('content', [])
            if target_content in content:
                matching_files.append(file_target_name)
                count += 1

  if matching_files:
        print(f"태그 '{target_content}'와 관련된 파일 목록:")
        print(f'총 {count}개의 파일을 찾았습니다.')
        print("찾은 파일 리스트")
        for matched_file in matching_files:

            print(matched_file)

  else:
        print(f"태그 '{target_content}'와 관련된 파일이 없습니다.")

def tag_finder():

  target_tag = input("찾을 태그를 입력하세요 : ")
  target_tag = target_tag.strip()

  files = [f for f in os.listdir('.') if os.path.isfile(f) and f.endswith('.json')]

  matching_files = []
  count = 0

  for file_target_name in files:
        with open(file_target_name, 'r') as file:
            file_data = json.load(file)
            tags = file_data.get('tags', [])
            if target_tag in tags:
                matching_files.append(file_target_name)
                count += 1


  if matching_files:
        print(f'총 {count}개의 파일을 찾았습니다.')
        print(f"태그 '{target_tag}'와 관련된 파일 목록:")
        for i,matched_file in enumerate(matching_files,start=1):
            print(f'{i} : {matched_file}')

  else:
        print(f"태그 '{target_tag}'와 관련된 파일이 없습니다.")

def name_finder():

  target_name = input("삭제할 파일의 이름 입력 : ")
  target_name = target_name.strip()+".json" # 앞뒤 공백 제거
  files = [f for f in os.listdir('.') if os.path.isfile(f) and f.endswith('.json')] # 현재 폴더에 있는 모든 디렉터리에 있는 json 파일을 검색하여 리스트에 저장

  matching_files = []
  count = 0

  for file_target_name in files:
        with open(file_target_name, 'r') as file:
          if file_target_name == target_name:
            matching_files.append(file_target_name)
            count += 1

  if matching_files:
        print(f'총 {count}개의 파일을 찾았습니다.')
        print(f"'{target_name}'파일 목록: ")
        for i,matched_file in enumerate(matching_files,start=1):
          print(f'{i} : {matched_file}')

  else:
      print(f"'{target_name}' 이름의 파일이 없습니다.")



print("파이썬 프로젝트 실행 (json 파일 형식만 지원)")

while True:
  print("=================================================================================================================")
  print("1. 파일 생성 2. 파일의 해시 값 찾기 3. 파일의 내용으로 파일 검색 4. 태그로 파일 검색 5. 파일 이름으로 검색 0 : 프로그램 종료")
  print("=================================================================================================================")

  choice = int(input("기능을 선택하세요 : "))

  if choice == 1:
    produce_file()

  elif choice == 2:
    find = input("해시 값을 찾을 파일의 이름 : ")+'.json'
    print(hash_find(find))

  elif choice == 3:
    content_finder()

  elif choice == 4:
    tag_finder()
 
  elif choice == 5:
    name_finder()

  else:
    print("프로그램을 종료 합니다.")
    break

 

# 제출 프로젝트 테스트 실행 예시

 

1. 파일 생성 두 번

2. 태그로 검색

3. 내용으로 검색

4. 파일 이름 으로 검색

5. 해시 값 출력

 

마무리

 

아쉬운 점

1. DFS로 하위 폴더 까지 검색 기능의 부재

2. 파일 삭제 기능 부재

3. 파일 생성 및 검색 등 기능 사용시 사용자가 디렉터리 지정 불가

 

배웠던 점

1. 프로젝트를 진행함에 있어 전체적인 틀 학습

2. OS모듈과 파이썬으로 json 파일 생성 및 탐색 기능 구현 경험

3. 배웠던 내용 복습 및 적용

- 딕셔너리와 json을 활용한 태그 기능

 

프로젝트의 깃 주소

https://github.com/pillow12360/FileFinder_python

 

'프로젝트 > 파일 내용 탐색 프로그램' 카테고리의 다른 글

프로젝트 보고서 작성  (0) 2023.10.18
5일차 태그 기능 추가  (2) 2023.10.16
4일차 기능 추가 및 선택지 추가  (0) 2023.10.15
3일차 본격적인 코드 구현  (0) 2023.10.14
glob 모듈  (0) 2023.10.12