본문 바로가기

기초코딩강좌/파이썬(Python) 기초 강좌

파이썬(Python) 예제 : 간단한 파일 관리자 프로그램

반응형

파일을 생성, 삭제, 목록 출력, 이름 변경 등의 기본적인 파일 관리 기능을 제공

import os

# 파일 생성 함수
def create_file(filename):
    with open(filename, 'w') as f:
        print(f"'{filename}' 파일이 생성되었습니다.")

# 파일 삭제 함수
def delete_file(filename):
    try:
        os.remove(filename)
        print(f"'{filename}' 파일이 삭제되었습니다.")
    except FileNotFoundError:
        print(f"'{filename}' 파일이 존재하지 않습니다.")

# 파일 이름 변경 함수
def rename_file(old_name, new_name):
    try:
        os.rename(old_name, new_name)
        print(f"'{old_name}' 파일이 '{new_name}'으로 이름이 변경되었습니다.")
    except FileNotFoundError:
        print(f"'{old_name}' 파일이 존재하지 않습니다.")

# 디렉터리 내 파일 목록 출력 함수
def list_files():
    files = os.listdir()
    if files:
        print("현재 디렉터리의 파일 목록:")
        for f in files:
            print(f" - {f}")
    else:
        print("디렉터리에 파일이 없습니다.")

# 프로그램 메인 루프
def main():
    print("파일 관리자 프로그램")
    print("1: 파일 생성\n2: 파일 삭제\n3: 파일 이름 변경\n4: 파일 목록 보기\n5: 종료")

    while True:
        choice = input("\n원하는 작업을 선택하세요 (1, 2, 3, 4, 5): ")

        if choice == '1':
            filename = input("생성할 파일 이름을 입력하세요: ")
            create_file(filename)

        elif choice == '2':
            filename = input("삭제할 파일 이름을 입력하세요: ")
            delete_file(filename)

        elif choice == '3':
            old_name = input("변경할 파일의 현재 이름을 입력하세요: ")
            new_name = input("변경할 새 파일 이름을 입력하세요: ")
            rename_file(old_name, new_name)

        elif choice == '4':
            list_files()

        elif choice == '5':
            print("프로그램을 종료합니다.")
            break

        else:
            print("잘못된 입력입니다. 1, 2, 3, 4, 5 중 하나를 선택하세요.")

if __name__ == "__main__":
    main()

 

코드 설명

  1. 파일 생성 (create_file): 지정된 이름의 파일을 생성하는 함수입니다. 파일이 생성되면 확인 메시지를 출력합니다.
  2. 파일 삭제 (delete_file): 입력된 이름의 파일을 삭제합니다. 파일이 존재하지 않을 경우 오류 메시지를 출력합니다.
  3. 파일 이름 변경 (rename_file): 파일의 이름을 변경합니다. 기존 파일이 존재하지 않으면 오류 메시지를 출력합니다.
  4. 파일 목록 출력 (list_files): 현재 디렉터리에 있는 모든 파일을 출력하여 사용자가 파일을 쉽게 확인할 수 있도록 합니다.
  5. 메인 루프 (main): 사용자 메뉴를 표시하고, 사용자가 원하는 작업을 선택할 수 있도록 합니다. 입력된 선택에 따라 적절한 함수가 호출됩니다. '5'를 선택하면 프로그램이 종료됩니다.
728x90
반응형