디필의 요모조모

파이썬 for Beginner 11장 연습문제 본문

Programming Language/Python

파이썬 for Beginner 11장 연습문제

Diphylleia12 2019. 12. 8. 17:55

1. 파일 입출력과 관련된 함수를 보기에서 모두 고르시오.

    input(), read(), readline(), print(), write(), writeline(), readlines()

 

2. 파일을 열고 한 줄 읽어서 출력하는 코드이다. 빈칸을 채우시오.

    inFp = open("C:/Temp/data1.txt", "r", encoding = "utf-8")

 

    inStr = inFp.readline()

    print(inStr, end = "")

 

    inFp.close()

 

3. 파일의 내용을 통째로 읽어서 리스트에 저장한 후 리스트의 내용을 하나씩 추출해 출력하는 코드이다. 빈칸을 채우시오.

    inFp = open("C:/Temp/data1.txt", "r", encoding = 'utf-8')

 

    inList = inFp.readlines()

    for inStr in inList :

        print(inStr, end = "")

    

    inFp.close()

 

4. open() 함수로 파일을 열려고 한다. 다음 중 파일이 없을 때 오류를 방지하는 함수는?

    ① os.path.file()
    ② os.path.error()
    ③ os.path.exists()
    ④ os.path.close()

 

5. 도스의 copy 명령어와 비슷하게 구현한 코드이다. 빈칸을 채우시오.

    inList = inFp.readlines()

    for inStr in inList :

        outFp.writelines(inStr)

 

6. 이진 파일을 읽거나 쓰는 데 사용하는 함수를 보기에서 모두 고르시오.

    input(), read(), readline(), print(), write(), writeline(), readlines()

 

7. 각 설명에 맞는 os, os.path, shutil 모듈의 함수를 쓰시오.

    ① 파일 복사                 shutil.copy(소스파일, 타깃파일)
    ② 디렉터리 복사           shutil.copytree(소스파일, 타깃파일)
    ③ 디렉터리 생성           os.mkdir(폴더명)
    ④ 디렉터리 삭제           shutil.rmtree(폴더명)
    ⑤ 폴더 여부 확인          os.path.exists(파일명 또는 폴더명)

    ⑥ 파일 삭제                 os.remove(파일명)

 

8. try~except 문에서 사용하는 예외 종류를 설명한 것이다. 예외를 쓰시오.

    ① 없는 변수에 접근할 때                       NameError
    ② 파일 처리에서 오류가 발생할 때           IOError
    ③ 실행에서 오류가 발생할 때                  RuntimeError
    ④ 딕셔너리에 키가 없을 때                     KeyError

 

9. (심화문제) 368쪽의 [응용예제 01]에 다음 기능을 추가하시오.

    ① 오른쪽 파일 리스트 상자에 파일 크기도 함께 표시한다. 1MB 미만은 KB 단위로 출력하고, 1MB 이상은 MB 단위            로 출력한다.
    ② 파일의 확장명에 따라서 색상을 다르게 나타낸다. 실행 파일인 exe, msi 등은 초록색, 그림 파일인 jpg, bmp, png,          gif 등은 빨간색, 파이썬 파일인 py는 파란색으로 나타낸다.

from tkinter import *
import os
import os.path
 
## 전역 변수 선언 부분 ##
window = None
searchDirList = ['C:\\']    # 검색한 폴더 목록의 스택
currentDir = 'C:\\'
dirLabel, dirListBox, fileListBox = None, None, None
 
## 함수 선언 부분 ##
def clickListBox(evt) :
    global currentDir, searchDirList    # 변경될 전역변수 
    if (dirListBox.curselection() == ()) : # 다른 리스트 box를 클릭할 떄는 무시
        return
    dirName = str(dirListBox.get(dirListBox.curselection())) # 클리한 폴더명
    if dirName == '상위폴더' :
        if len(searchDirList) == 1 : # 상위 폴더를 클릭했는데 현재 C:\\면 무시
            return
        searchDirList.pop() # 상위 폴더 이동이라 마지막 검색 폴더(현재 폴더) pop
    else :
        searchDirList.append(currentDir + dirName + '\\') #검색 리스트에 클릭한 폴더 추가
         
    fillListBox()
         
def fillListBox() :
    global currentDir, searchDirList, dirLabel, dirListBox, fileListBox
    dirListBox.delete(0 ,END)   # 폴더 리스트 box를 비움
    fileListBox.delete(0, END)  # 파일 리스트 box를 비움
 
    dirListBox.insert(END, "상위폴더")
    currentDir = searchDirList[len(searchDirList) - 1]
    dirLabel.configure(text = currentDir)
    folderList = os.listdir(currentDir)
 
    index = 0   # 파일 목록 위치
    for item in folderList :
        if os.path.isdir(currentDir + item) :
            dirListBox.insert(END, item)
        elif os.path.isfile(currentDir + item) :
            fileSize = os.path.getsize(currentDir + item)    # 파일 사이즈 저장 (Byte 단위)
            fileName, fileExt = os.path.splitext(item)  # 파일 이름과 확장자를 튜플로 분리
 
            if fileSize < 1000000 :   # 1MB 미만
                fileSize = fileSize // 1000     # KB 단위로 (소수점 x)
                fileListBox.insert(END, item + "   " + "[" + str(fileSize) + " KB]")
            elif 1000000 <= fileSize :
                fileSize = fileSize // 1000000     # MB 단위로 (소수점 x)
                fileListBox.insert(END, item + "   " + "[" + str(fileSize) + " MB]")
 
            fileExt = fileExt.lower()     # 대문자 확장자일 경우 소문자로 변환
            if fileExt == '.exe' or fileExt == '.msi' :     # 확장자 별로 분류
                fileListBox.itemconfig(index, foreground = "green")
            elif fileExt == '.jpg' or fileExt == '.bmp' or fileExt == '.png' or fileExt == '.gif' :
                fileListBox.itemconfig(index, foreground = "red")
            elif fileExt == '.py' :
                fileListBox.itemconfig(index, foreground = "blue")
             
            index += 1
 
## 메인 코드 부분 ##
window = Tk()
window.title("폴더 및 파일 목록 보기")
window.geometry("300x500")
 
dirLabel = Label(window, text = currentDir)
dirLabel.pack()
 
dirListBox = Listbox(window)
dirListBox.pack(side = LEFT, fill = BOTH, expand = 1)
dirListBox.bind('<<ListboxSelect>>', clickListBox)
 
fileListBox = Listbox(window)
fileListBox.pack(side = RIGHT, fill = BOTH, expand = 1)
 
fillListBox()   # 초기에는 C:\\의 모든 폴더 목록 만들기
 
window.mainloop()

 

Comments