{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "***\n", "***\n", "# 14. 파일과 디렉토리 다루기\n", "***\n", "***" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "***\n", "## 1 파일 다루기\n", "***" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 1-1 파일 목록 얻기\n", "- os.listdir('경로')\n", " - 디렉토리 안에 들어 있는 각 파일 목록 반환" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['python10.ipynb', 'python09.ipynb', 'python12.ipynb', 'python14.ipynb', 'cal.py', 'example', 'python13.ipynb', 'python11.ipynb', 'python08.ipynb', 'python15.ipynb', 'dog.jpeg', 'python02.ipynb', 'python04.ipynb', 'python06.ipynb', '.ipynb_checkpoints', 'python01.ipynb', 'Assignment01.ipynb', 'python03.ipynb', 'python07.ipynb', 'python05.ipynb']\n", "\n", "['.DS_Store', 'LICENSE', 'images', 'python3.6', 'README.md', '.git']\n" ] } ], "source": [ "import os\n", "# Winodws (90%), Mac OS, Linux\n", "\n", "print(os.listdir('.')) # 현재 디렉토리의 파일 목록 얻기\n", "print()\n", "\n", "print(os.listdir('../')) # 현재 디렉토리의 부모 디렉토리의 파일 목록 얻기" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 1-2 파일 종류 알아보기\n", "- os.path 모듈의 다음 함수들은 파일의 종류를 판단하여 True 또는 False를 반환한다.\n", " - isfile(filepath)\n", " - 순수 파일이면 True\n", " - isdir(filepath)\n", " - 디렉토리이면 True\n", " - islink(filepath)\n", " - 심볼릭링크이면 True" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "python10.ipynb :Regular file\n", "python09.ipynb :Regular file\n", "python12.ipynb :Regular file\n", "removeme.txt :Regular file\n", "python14.ipynb :Regular file\n", "cal.py :Regular file\n", "t1.txt :Regular file\n", "python13.ipynb :Regular file\n", "python11.ipynb :Regular file\n", "python08.ipynb :Regular file\n", "pickle.txt :Regular file\n", "dog.jpeg :Regular file\n", "python02.ipynb :Regular file\n", "t.txt :Regular file\n", "python04.ipynb :Regular file\n", "pickle2.txt :Regular file\n", "python06.ipynb :Regular file\n", ".ipynb_checkpoints :Directory\n", "python01.ipynb :Regular file\n", "Assignment01.ipynb :Regular file\n", "python03.ipynb :Regular file\n", "output.txt :Regular file\n", "python07.ipynb :Regular file\n", "python05.ipynb :Regular file\n" ] } ], "source": [ "import os\n", "def filetype(fpath):\n", " print(fpath, ':', end=\"\")\n", " \n", " if os.path.isfile(fpath):\n", " print('Regular file')\n", " \n", " if os.path.isdir(fpath):\n", " print('Directory')\n", "\n", " if os.path.islink(fpath):\n", " print('Symbolic link')\n", " \n", "flist = os.listdir('.')\n", "for fname in flist:\n", " filetype(fname)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 1-3 파일의 허가권\n", "#### 1) 파일의 허가권 알아보기\n", "- os.access(filepath, mode)\n", " - mode에 들어갈 값\n", " - os.F_OK: 파일 자체가 존재하는 것을 테스트\n", " - os.R_OK: 읽기 권한이 있는 것을 테스트\n", " - os.W_OK: 쓰기 권한이 있는 것을 테스트\n", " - os.X_OK: 실행 권한이 있는 것(또는 디렉토리인지)을 테스트" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "python10.ipynb :Exists - RW\n", "python09.ipynb :Exists - RW\n", "python12.ipynb :Exists - RW\n", "removeme.txt :Exists - RW\n", "python14.ipynb :Exists - RW\n", "cal.py :Exists - RW\n", "t1.txt :Exists - RW\n", "python13.ipynb :Exists - RW\n", "python11.ipynb :Exists - RW\n", "python08.ipynb :Exists - RW\n", "pickle.txt :Exists - RW\n", "dog.jpeg :Exists - RW\n", "python02.ipynb :Exists - RW\n", "t.txt :Exists - RW\n", "python04.ipynb :Exists - RW\n", "pickle2.txt :Exists - RW\n", "python06.ipynb :Exists - RW\n", ".ipynb_checkpoints :Exists - RWX\n", "python01.ipynb :Exists - RW\n", "Assignment01.ipynb :Exists - RW\n", "python03.ipynb :Exists - RW\n", "output.txt :Exists - RW\n", "python07.ipynb :Exists - RW\n", "python05.ipynb :Exists - RW\n" ] } ], "source": [ "import os\n", "def fileaccess(fpath):\n", " print(fpath, ':', end=\"\")\n", " \n", " if os.access(fpath, os.F_OK): \n", " print('Exists - ', end=\"\")\n", " else: \n", " return\n", " \n", " if os.access(fpath, os.R_OK): \n", " print('R', end=\"\")\n", " \n", " if os.access(fpath, os.W_OK): \n", " print('W', end=\"\")\n", " \n", " if os.access(fpath, os.X_OK): \n", " print('X', end=\"\")\n", " print()\n", " \n", "flist = os.listdir('.')\n", "for fname in flist:\n", " fileaccess(fname)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### 2) 파일의 허가권 변경하기\n", "- os.chmod(filepath, mode)" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "ename": "FileNotFoundError", "evalue": "[Errno 2] No such file or directory: 'output.txt'", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mFileNotFoundError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mos\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mchmod\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'output.txt'\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m0o777\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;31m# 리눅스에서의 실행 예\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 2\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 3\u001b[0m \u001b[0mget_ipython\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mrun_line_magic\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'ls'\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m'-al output.txt'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", "\u001b[0;31mFileNotFoundError\u001b[0m: [Errno 2] No such file or directory: 'output.txt'" ] } ], "source": [ "os.chmod('output.txt', 0o777) # 리눅스에서의 실행 예\n", "\n", "%ls -al output.txt" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 1-4 파일 조작하기\n", "#### 1) 파일 이름 변경하기\n", "- os.rename(old_filepath, new_filepath)" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [], "source": [ "s = \"\"\"Its power: Python developers typically report \n", "they are able to develop applications in a half\n", "to a tenth the amount of time it takes them to do\n", "the same work in such languages as C.\"\"\"\n", "\n", "with open('t.txt', 'w') as f:\n", " f.write(s) # 문자열을 파일에 기록" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "False\n", "True\n" ] } ], "source": [ "import os\n", "os.rename('t.txt', 't1.txt') # t.txt를 t1.txt로 바꾼다\n", "print(os.access('t.txt', os.F_OK))\n", "print(os.access('t1.txt', os.F_OK))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### 2) 파일 이동하기\n", "- os.rename(old_filepath, new_filepath)" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [], "source": [ "os.mkdir('example') " ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "True\n" ] } ], "source": [ "os.rename('t1.txt', './example/t1.txt') # 현재 작업 디렉토리의 t1.txt를 example에 t1.txt이름으로 옮긴다.\n", "print(os.access('./example/t1.txt', os.F_OK))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### 3) 파일 복사하기\n", "- shutil 모듈 활용\n", "- shutil.copyfile(src_filepath, dest_filepath)" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "True\n" ] } ], "source": [ "import shutil\n", "shutil.copyfile('output.txt', 'output_new.txt')\n", "print(os.access('output_new.txt', os.F_OK))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 1-5 파일 이름 다루기" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### 1) 상대 경로를 절대 경로로 변환하기 [중요]\n", "- os.path.abspath(상대경로)\n", " - 실제 파일 존재와는 무관하게 절대경로로 변경함" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "/Users/jubong/git/python-link-e-learning/python3.6/o.txt\n" ] } ], "source": [ "import os\n", "print(os.path.abspath('o.txt'))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### 2) 주어진 경로의 파일이 존재하는지 확인 [중요]\n", "- os.path.exists(filepath)" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "True\n", "True\n", "False\n" ] } ], "source": [ "f = '/Users/jubong/git/python-link-e-learning/'\n", "print(os.path.exists(f))\n", "print(os.path.exists('t1.txt'))\n", "print(os.path.exists('asdf.txt'))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### 3) 현재/부모 디렉토리를 가리키는 이름 얻기" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ ".\n", "..\n" ] } ], "source": [ "print(os.curdir) #현재 디렉토리\n", "print(os.pardir) #부모 디렉토리" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### 4) 디렉토리 분리 문자 얻기" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "/\n" ] } ], "source": [ "print(os.sep)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 1-6 경로명 분리하기" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### 1) 경로와 파일명으로 분리" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "t1.txt\n", "/Users/jubong/git/python-link-e-learning\n" ] } ], "source": [ "f = '/Users/jubong/git/python-link-e-learning/t1.txt'\n", "\n", "print(os.path.basename(f)) # 파일명만 추출\n", "print(os.path.dirname(f)) # 디렉토리 경로 추출" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### 2) 경로명과 파일명을 한번에 분리" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "('/Users/yhhan/git/python-e-learning', 't.txt')\n" ] } ], "source": [ "print(os.path.split(f))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### 3) MS 윈도우즈에서 드라이브명과 파일 경로명을 분리" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "('', '/Users/yhhan/git/python-e-learning/t.txt')\n" ] } ], "source": [ "print(os.path.splitdrive(f))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### 4) 확장자 분리" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "('/Users/yhhan/git/python-e-learning/t', '.txt')\n" ] } ], "source": [ "print(os.path.splitext(f))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 1-7 경로명 생성하기 [중요]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- Linux and Mac" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "/Users/jubong/git/python-link-e-learning/t.txt\n" ] } ], "source": [ "path = os.path.join(\"/\", \"Users\", \"jubong\", \"git\", \"python-link-e-learning\", \"t.txt\")\n", "print(path)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- Windows" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "c:\\/Users/jubong\n" ] } ], "source": [ "path = os.path.join(\"c:\\\\\", \"Users\", \"jubong\")\n", "print(path)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "***\n", "## 2 디렉토리 다루기\n", "***" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 2-1 디렉토리에 관련된 일반 작업" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### 1) 현재 작업 디렉토리 알아보기" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "/Users/jubong/git/python-link-e-learning/python3.6\n" ] } ], "source": [ "import os\n", "print(os.getcwd())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### 2) 작업 디렉토리 변경하기" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "/Users/jubong/Public\n" ] } ], "source": [ "path = os.path.join(\"/\", \"Users\", \"jubong\", \"Public\")\n", "#path = os.path.join(\"c:\\\\\", \"Users\", \"jubong\", \"Public\") \n", "\n", "os.chdir(path)\n", "print(os.getcwd())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### 3) 디렉토리 만들기" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "error: invalid character '\u0000' in LSCOLORS env var\n", "total 0\n", "drwxr-xr-x 3 jubong staff 96 9 21 15:00 \u001b[1m\u001b[36m.\u001b[m\u001b[m/\n", "drwxrwxrwx+ 8 jubong staff 256 9 22 09:35 \u001b[33m..\u001b[m\u001b[m/\n", "drwxr-xr-x 3 jubong staff 96 9 21 15:00 \u001b[1m\u001b[36mlevel1\u001b[m\u001b[m/\n", "True\n", "True\n", "True\n" ] } ], "source": [ "import os\n", "\n", "os.mkdir('temp1') # 0755 기본 모드(rwxr-xr-x)로 만들어짐\n", "%ls -al temp\n", "# os.mkdir('temp2', 0700) # 0700 모드(rwx------)로 만들어짐\n", "\n", "os.mkdir('temp2', 0o700)\n", "os.makedirs('temp2/level1/level2') #0755 기본 모드, 중간에 필요한 디렉토리도 모두생성\n", "\n", "print(os.access('/Users/jubong/Public/temp1', os.F_OK))\n", "print(os.access('/Users/jubong/Public/temp2', os.F_OK))\n", "print(os.access('/Users/jubong/Public/temp/level1/level2', os.F_OK))" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [], "source": [ "import os\n", "\n", "os.mkdir('temp3', 0o700)\n", "\n", "path = os.path.join(\"temp3\", \"level1\", \"level2\")\n", "os.makedirs(path) #0755 기본 모드, 중간에 필요한 디렉토리도 모두생성" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### 4) 디렉토리 삭제" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [], "source": [ "os.rmdir('temp1') #디렉토리에 내용이 없을 때 삭제가능" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "ename": "OSError", "evalue": "[Errno 66] Directory not empty: 'temp3'", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mOSError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mos\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mrmdir\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'temp3'\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;31m#디렉토리에 다른 파일이 있으면 삭제할 수 없음\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mOSError\u001b[0m: [Errno 66] Directory not empty: 'temp3'" ] } ], "source": [ "os.rmdir('temp3') #디렉토리에 다른 파일이 있으면 삭제할 수 없음" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### 5) 다단계 디렉토리 삭제\n", "- os.removedirs(filepath)\n", " - filepath에 지정된 디렉토리들 중 맨 오른쪽 디렉토리 부터 차례차례로 삭제한다.\n", " - 디렉토리에 다른 파일이 있으면 삭제하기 않고 중단" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [], "source": [ "os.removedirs('temp2/level1/level2')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### 6) 하위 디렉토리까지 모두 한번에 삭제\n", "- shutil.rmtree() \n", " - 파일은 물론 하위 디렉토리까지 모두 한번에 삭제 가능\n", " - 조심해서 사용해야 함" ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [ { "ename": "FileExistsError", "evalue": "[Errno 17] File exists: 'temp'", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mFileExistsError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;32mimport\u001b[0m \u001b[0mos\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 3\u001b[0;31m \u001b[0mos\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mmkdir\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'temp'\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;31m# 0755 기본 모드(rwxr-xr-x)로 만들어짐\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 4\u001b[0m \u001b[0mos\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mmakedirs\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'temp/level1/level2'\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;31m#0755 기본 모드, 중간에 필요한 디렉토리도 모두생성\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 5\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n", "\u001b[0;31mFileExistsError\u001b[0m: [Errno 17] File exists: 'temp'" ] } ], "source": [ "import os\n", "\n", "os.mkdir('temp') # 0755 기본 모드(rwxr-xr-x)로 만들어짐\n", "os.makedirs('temp/level1/level2') #0755 기본 모드, 중간에 필요한 디렉토리도 모두생성\n", "\n", "print(os.access('/Users/jubong/Public/temp', os.F_OK))\n", "print(os.access('/Users/jubong/Public/temp/level1/level2', os.F_OK))" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [], "source": [ "import shutil\n", "shutil.rmtree('temp3')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### 7) 디렉토리 복사\n", "- shutil.copytree(src_filepath, dest_filepath)\n", " - 하위 디렉토리와 파일등을 지니고 있는 디렉토리를 복사" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [ { "ename": "FileExistsError", "evalue": "[Errno 17] File exists: 'myweb_backup'", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mFileExistsError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0mos\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mmkdir\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'temp/temp2'\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m0o700\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0mshutil\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mcopytree\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'temp'\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m'myweb_backup'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;32m~/anaconda3/lib/python3.6/shutil.py\u001b[0m in \u001b[0;36mcopytree\u001b[0;34m(src, dst, symlinks, ignore, copy_function, ignore_dangling_symlinks)\u001b[0m\n\u001b[1;32m 319\u001b[0m \u001b[0mignored_names\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mset\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 320\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 321\u001b[0;31m \u001b[0mos\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mmakedirs\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mdst\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 322\u001b[0m \u001b[0merrors\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m[\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 323\u001b[0m \u001b[0;32mfor\u001b[0m \u001b[0mname\u001b[0m \u001b[0;32min\u001b[0m \u001b[0mnames\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", "\u001b[0;32m~/anaconda3/lib/python3.6/os.py\u001b[0m in \u001b[0;36mmakedirs\u001b[0;34m(name, mode, exist_ok)\u001b[0m\n\u001b[1;32m 218\u001b[0m \u001b[0;32mreturn\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 219\u001b[0m \u001b[0;32mtry\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 220\u001b[0;31m \u001b[0mmkdir\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mname\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mmode\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 221\u001b[0m \u001b[0;32mexcept\u001b[0m \u001b[0mOSError\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 222\u001b[0m \u001b[0;31m# Cannot rely on checking for EEXIST, since the operating system\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", "\u001b[0;31mFileExistsError\u001b[0m: [Errno 17] File exists: 'myweb_backup'" ] } ], "source": [ "os.mkdir('temp/temp2', 0o700)\n", "shutil.copytree('temp', 'myweb_backup')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 2-2 디렉토리(트리) 탐색하기\n", "- os.walk(filepath)\n", " - filepath 부터 시작하여 재귀적으로 모든 하위 디렉토리까지 탐색을 하는 함수\n", " - 탐색시 발견하는 모든 파일에 대해서는 다음 튜플을 리턴함\n", " - (dirpath, dirnames, filemnames)\n", " - dirpath: 탐색하고 있는 디렉토리 경로\n", " - dirnames: dirpath 안에 존재하는 서브 디렉토리의 리스트\n", " - filenames: dirpath 안에 존재하는 파일 리스트" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 아래 예는 현재 디렉토리부터 모든 하위 디렉토리 내에 존재하는 모든 txt 파일을 삭제하는 프로그램" ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [ { "ename": "FileNotFoundError", "evalue": "[Errno 2] No such file or directory: '/Users/yhhan/Public'", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mFileNotFoundError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0;31m#path = os.path.join(\"c:\\\\\", \"Users\", \"yhhan\", \"Public\")\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 3\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 4\u001b[0;31m \u001b[0mos\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mchdir\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mpath\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 5\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mos\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mgetcwd\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", "\u001b[0;31mFileNotFoundError\u001b[0m: [Errno 2] No such file or directory: '/Users/yhhan/Public'" ] } ], "source": [ "path = os.path.join(\"/\", \"Users\", \"yhhan\", \"Public\")\n", "#path = os.path.join(\"c:\\\\\", \"Users\", \"yhhan\", \"Public\") \n", "\n", "os.chdir(path)\n", "print(os.getcwd())" ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "/Users/jubong/Public/temp\n", "\n", "removing /Users/jubong/Public/temp/t.txt\n", "removing /Users/jubong/Public/temp/level1/t.txt\n", "removing /Users/jubong/Public/temp/level1/level2/t.txt\n", "\n", "/Users/jubong/Public\n" ] } ], "source": [ "if os.path.exists('temp'):\n", " shutil.rmtree('temp')\n", "\n", "path = os.path.join(\"temp\", \"level1\", \"level2\")\n", "os.makedirs(path)\n", "\n", "with open(os.path.join(\"temp\", \"t.txt\"), \"w\") as f:\n", " f.write(\"aaa\")\n", " \n", "with open(os.path.join(\"temp\", \"level1\", \"t.txt\"), \"w\") as f:\n", " f.write(\"aaa\")\n", " \n", "with open(os.path.join(\"temp\", \"level1\", \"level2\", \"t.txt\"), \"w\") as f:\n", " f.write(\"aaa\")\n", "\n", "path = os.path.join(\"temp\")\n", "os.chdir(path)\n", "print(os.getcwd())\n", "print()\n", "for path, subdirs, files in os.walk(os.getcwd()):\n", " for fname in files:\n", " if fname.endswith('.txt'):\n", " fullpath = os.path.join(path, fname)\n", " print('removing', fullpath)\n", " os.remove(fullpath)\n", "\n", "print()\n", "os.chdir(\"..\")\n", "print(os.getcwd())" ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "/Users/jubong/git/python-link-e-learning\n", "\n", "removing /Users/jubong/git/python-link-e-learning/python3.6/t1.txt\n" ] } ], "source": [ "import os\n", "os.chdir('/Users/jubong/git/python-link-e-learning')\n", "print(os.getcwd())\n", "print()\n", "for path, subdirs, files in os.walk(os.getcwd()):\n", " for fname in files:\n", " if fname.endswith('.txt'):\n", " fullpath = os.path.join(path, fname)\n", " print('removing', fullpath)\n", " os.remove(fullpath)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "

참고 문헌: 파이썬(열혈강의)(개정판 VER.2), 이강성, FreeLec, 2005년 8월 29일

" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.8" } }, "nbformat": 4, "nbformat_minor": 1 }