파일을 읽고 쓰는 프로그램을 만들어보자
import os
import os.path
print("="*34, " 메모장 ", "="*34)
while True :
menu = input("(1)파일쓰기(2)파일읽기(3)파일목록보기(4)파일삭제(5)폴더생성(6)폴더삭제(7)종료>>")
print("-"*78)
# 파일 쓰기
if menu == "1" :
# 저장할 파일명과 내용을 입력받는다
fname = input("저장할 파일명을 입력하세요 >> ")
data = input("저장할 내용을 입력하세요 >> ")
path = os.path.join("./data", fname)
f = open(path, "w")
f.write(data)
f.close()
# 파일 읽기
elif menu == "2" :
fname = input("읽을 파일명을 입력하세요 >> ")
path = os.path.join("./data", fname)
if os.path.exists(path) :
f = open(path, "r")
data = f.read()
print(data, end="")
f.close()
else :
print("파일이 없습니다")
# 목록보기
elif menu == "3" :
# 목록을 경로 입력
path = input("경로를 입력하세요 >> ")
filenames = os.listdir(path)
for filename in filenames :
full_path = os.path.join(path, filename)
print(full_path)
# 파일 삭제
elif menu == "4" :
path_base = "./data"
fname = input("삭제할 파일명을 입력하세요 >> ")
path = os.path.join(path_base, fname)
if os.path.exists(path) :
os.remove(path)
else :
print("해당 파일이 없습니다")
# 폴더 생성
elif menu == "5" :
path_base = "./data"
directory = input("생성할 폴더명을 입력하세요 >> ")
path = os.path.join(path_base, directory)
if not os.path.exists(path) :
os.mkdir(path)
else :
print("해당 폴더가 존재합니다")
# 폴더 삭제
elif menu == "6" :
path_base = "./data"
directory = input("삭제할 폴더명을 입력하세요 >> ")
path = os.path.join(path_base, directory)
if os.path.exists(path) :
os.rmdir(path)
else :
print("해당 폴더가 없습니다")
elif menu == "7" :
print("메모장을 종료합니다")
break