본문 바로가기
인터페이스 개발/Python

Python - 파일[파일 관리] - 파일 관리 함수, 디렉토리 관리함수

by cooluk 2020. 7. 27.

Chap.14 파일[파일 관리] - 파일 관리 함수, 디렉토리 관리함수

 

파일 관리

파일 관리 함수, 디렉토리 관리함수

 

파일 관리 함수

  • shutil.copy(a, b)

  • shutil.move(a, b)

  • shutil.rmtree(path) # 비어있는 directory만 삭제 가능

  • os.rename(a, b)

  • os.remove(f)

  • 리눅스 용

  • os.chmod(f, m)

  • shutil.chown(f, u, g)

  • os.link(a, b)

  • os.symlink(a, b)

import shutil

shutil.copy("live.txt", "live2.txt")

 

디렉토리 관리 함수

  • os.chdir(d) # change

  • os.mkdir(d) # make (이미 존재하면 예외)

  • os.rmdir(d) # remove

  • os.getcwd() # 현재 working directory 문자열 리턴

  • os.listdir(d) # directory 목록

  • glob.glob(pattern)

  • os.path.isabs(f) # 절대경로 검사

  • os.path.abspath(f) # 상대경로 -> 절대경로

  • os.path.realpath(f)

  • os.path.exists(f) # 경로 존재 검사 ☆

  • os.path.isfile(f) # 파일인지 검사

  • os.path.isdir(f) # directory인지 검사

is로 시작하는 함수는 True, False만 리턴

 

import os

files = os.listdir('/workspace/01_Python')
for f in files:
    print(f)

결과

chapter10
chapter11
chapter12
chapter13
chapter14
chapter3
chapter4
chapter5
chapter6
chapter7
chapter8
chapter9
ex01.py

터미널 창에서 dir /b 와 같다.

 

file directory 모두 출력

import os

def dumpdir(path):
    files = os.listdir(path)
    for f in files:
        fullpath = os.path.join(path, f)  # 두 문자열을 결합하는데 \ 얘를 끼워줌
                                          # file과 directory를 결합할때 사용
                                          # OS마다 달라 번거로울 때 이용
        if os.path.isdir(fullpath):
            print("[%s]"%fullpath)
            dumpdir(fullpath)  # 재귀호출
        else:
            print("\t" + f)
dumpdir("/workspace/01_Python")

 

Chap.14 파일[데이터베이스]은 데이터베이스 배운 뒤에~

 

 

 

예제

data = [
[1,2,3,54,45],
[7,8,3,4,5],
[1,12,13,4,25]

]

"data.csv" 이름의 파일로 저장하세요.

def save(fpath, data):
    f=open(fpath,"wt")
    for l in data:
        l = map(str, l)  # ★★정수형을 문자열로★★★★★★★ 모르면 노가다
        row = ','.join(l)  # ★ 모르면 노가다 csv 파일을 위해 ',' 넣어준다.
        f.write(row + "\n")
    f.close()

def main():
    data = [
        [1, 2, 3, 54, 45],
        [7, 8, 3, 4, 5],
        [1, 12, 13, 4, 25]
    ]

    save("data.csv", data)

main()

 

"data.csv" 이름의 파일로 저장하세요.(with ~ as 이용)

def save(fpath, data):
   try:
        with open(fpath,"wt") as f:  # f = open(fpath, "wt")과 동일
            for l in data:
                l = map(str, l)
                row = ','.join(l)
                f.write(row + "\n")
   except Exception as e:  # 모든 예외 처리
       print(e)

def main():
    data = [
        [1, 2, 3, 54, 45],
        [7, 8, 3, 4, 5],
        [1, 12, 13, 4, 25]
    ]

    save("data.csv", data)

main()

 

 

원래대로 복원

def load(fpath):
    f = open(fpath, "rt")
    lines = f.readlines()
    data = []
    for line in lines:
        print(line, end='')  # 한줄의 문자열이 출력된다.
        row = line.split(',')
        print(row)  # ,를 기준으로 split 된 문자열이 출력된다.
        row = list(map(int, row))  # 문자열 요소를 정수 요소로 변환
        print(row)  # white space 문자 또한 없어진다!
        data.append(row)
    f.close()
    return data


def main():

    data = load("data.csv")
    print(data)


main()

(이중)리스트는 binary(구조가 있다.)이다. (text data가 아니면 다 binary)
binary <-> text 변환에서 과정이 필요하다.

 

원래대로 복원(with ~ as 이용)

def load(fpath):
    try:
        with open(fpath, "rt") as f:  # f = open(fpath, "rt")과 동일
            lines = f.readlines()
            data = []
            for line in lines:
                print(line, end='')
                row = line.split(',')
                print(row)
                row = list(map(int, row))
                print(row)
                data.append(row)
            return data
    except Exception as e:
        print(e)


def main():

    data = load("data.csv")
    print(data)

main()

 

댓글