0% found this document useful (0 votes)
2 views27 pages

11 OS&ShutilModules

Uploaded by

haeinpark1376
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views27 pages

11 OS&ShutilModules

Uploaded by

haeinpark1376
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

Lecture 11

OS and Shutil Modules


Prof. Hyeong-Seok Ko
Seoul National University
Dept. of Electrical and Computer Engineering

Files to have at your 바탕화면:


• folderPractice.zip
What is directory?
• Directory ≡ folder

옛날에는 folder라는 용어가 없었고 대신 directory라는 용어를 사용했음.


What is cmd prompt?

• MS Windows OS 가 출시되기 전에는 DOS 가 있었음


– DOS 는 disk operating system 의 약어임
– 운영체제(OS)의 일종인데 이 때는 GUI 도 없었고 (mouse 도 없었고) 오로지 keyboard 를 이
용해서 명령어를 입력해야 했음.
• cmd prompt (명령 프롬프트) DOS의 요즈음 형태임
– text-based interface

여기에 keyboard 로 명령어 입력


Unzip folderPractice.zip to your 바탕화면.
A Little Taste of cmd • abcPQR/
• defSTU/
• dir • Z/
– directory • shutilTest_05.py
• cd ... (in my case OneDrive)
– change directory
• dir
• Somehow cd to folderPractice
• cd abcPQR; dir
• cd abPQ; dir
• copy list5.txt x.txt; dir
• ↑ (up arrow)
– repeats the previous command
• del x.txt; dir
• cd ../../defSTU; dir
• rename test.txt TEST.txt; dir
• cd ../Z; dir
• mkdir Y; dir
• move list.txt Y; dir
• cd Y; dir
• move list.txt ..
• cd ..
• rmdir Y
Now, MS Windows

• 파일탐색기를 열기
• Visit folderPractice/abcPQR/abPQ.
– MS Windows 에서는 mouse 로 더블클릭을 해 나감.
• Create a copy of list5.txt.
– Ctrl + C; Ctrl + V;
• Delete that copy.
Parent Directory vs. Subdirectory

• 내PC → 바탕화면 → folderPractice → abcPQR → abPQ


상위 하위

• 내PC는 최상위 디렉토리 (root directory)


• folderPractice는 바탕화면의 하위 폴더
• folderPractice는 abcPQR 의 상위 폴더
How to express a path in text?
• What is a path?
• Why do we need to express a path in text?
– Often you have to specify a directory in the code.
– In such a case, you have to do it using text.

exampleCode.py

Python program은 글로만 작성할 수 있으니


폴더의 위치를 글로 알려줘야 함.
How to Write a Path in Text?
• .
– Current directory
• .. • Somehow cd to folderPractice
– Parent directory • cd abcPQR/abPQ; dir
• / • cd abPQ; dir
• cd ../../defSTU; dir
– Separator between the directories.
• cd ../Z; dir
– Note that
• cmd prompt 에서 폴더 간 구분 문자는 \ 임
• 그런데 python coding에서는 \ 대신 / 를 사용함.
Absolute Path vs. Relative Path
folderPractice:
• You are at abPQ. • abcPQR/
• Relative path to Z: • defSTU/
• Z/
– 현재 위치를 기준으로 하여 목적지까지의 경로 • shutilTest_05.py
– ANS:
../../Z
• Absolute path
– 처음부터 시작하여 목적지까지의 경로
– ANS:
C:\Users\hsko1\OneDrive\바탕 화면\folderPractice\Z

Click here,
then you can find the absolute path.
Programming Practice
using OS Module

Move to folderPractice/Z.
You should be in folderPractice/Z.
getcwd()
• Returns current working directory as a string.

import os

print()
print(os.getcwd())
print()

C:\Users\hsko1\OneDrive\바탕 화면\folderPractice\Z
listdir()
• Returns a list containing the names of the entries in the directory given by path.

pythonTest_02.py
import os
print(os.listdir())

['list.txt', 'Objs', 'Old_Maid_Hands.txt',


'pythonTest_01.py', 'pythonTest_02.py',
'pythonTest_03.py', 'pythonTest_04.py',
'pythonTest_05.py', 'pythonTest_06.py',
'pythonTest_07.py', 'shutilTest_02.py',
'shutilTest_03.py', 'shutilTest_04.py',
'ZZ']
chdir(path)
• Changes the current working directory to the given path.

pythonTest_03.py
import os
parentDir = ".."
# parentDir = "../" is also fine
os.chdir(parentDir)
print(os.getcwd())
subDir = "./abcPQR"
os.chdir(subDir)
print(os.getcwd())

C:\Users\hsko1\OneDrive\바탕 화면\folderPractice
C:\Users\hsko1\OneDrive\바탕 화면\folderPractice\abcPQR
makedirs(path, exist_ok=True/False)
• Makes the directories with the specified path.
– exist_ok (optional): if the path already exists, error occurs if the value is False.

pythonTest_04.py
import os
newDir = "./MySubFolder"
# newDir = "MySubFolder" is also fine
os.makedirs(newDir)
os.makedirs(newDir) # error
os.makedirs(newDir, exist_ok=True) # ok
removedirs(path)
• Removes the directories in the specified path.

pythonTest_05.py
import os
os.removedirs("./MySubFolder")
isfile(path), isdir(path), exists(path)
• isfile(path)
– Returns True if the path is an existing file.
• isdir(path)
– Returns True if the path is an existing directory.
• exists(path)
– Returns True if there exists a file or directory.

pythonTest_06.py
import os
newDir = "./MySubFolder"
os.makedirs(newDir, exist_ok=True)
x = "./pythonTest_01.py"
y = "./MySubFolder"
print(os.path.isfile(x), os.path.isfile(y)) True False
print(os.path.isdir(x), os.path.isdir(y)) False True
print(os.path.exists(x), os.path.exists(y)) True True
rename(old, new)
• Renames the file or directory from old to new.

pythonTest_07.py
import os
oldDirName = "./MySubFolder"
newDirName = "./MyNewSubFolder"
oldFileName = "./pythonTest_01.py"
newFileName = "./pythonTest_01NEW.py"
os.rename(oldDirName, newDirName)
os.rename(oldFileName, newFileName)
Programming Practice
using Shutil Module
https://en.wikipedia.org/wiki/Shell_(computing)
Shutil
• Shell utilities
• What is Shell?
– A computer program that exposes an operating system’s services to a human user or other
programs.
– Command-Line Interface (CLI) vs. Graphical User Interface (GUI)
– You can think shell = cmd prompt in this class.

cmd.exe (CLI) File Explorer (GUI)


Moving a File to a Folder
• In the cmd prompt, execute: move list.txt ZZ
• Go to ZZ.

shutil_01.py
import shutil

sourceFile = "list.txt"
targetFolder = "../"
shutil.move(sourceFile, targetFolder)
Moving a Folder to a Folder

If target folder doesn’t exists, If target folder exists,

shutil_02.py
import shutil

sourceFolder = "Objs"
targetFolder = "New_Objs"
shutil.move(sourceFolder, targetFolder)
Copying a File to another File: copyfile()

shutil_03.py
import shutil

sourceFile = "Old_Maid_Hands.txt"
targetFile = "New_Old_Maid_Hands.txt"
shutil.copyfile(sourceFile, targetFile)
Copying a File to a Folder: copy()

shutil_04.py
import shutil

sourceFile = "IMG_SNU.png"
targetFolder = "Image"
shutil.copy(sourceFile, targetFolder)
# shutil.copy2(sourceFile, targetFolder)
copyfile() vs. copy() vs. copy2()
• copyfile()
– just copies the contents of the file.

• copy()
– Copyfile() + copymode
• copymode: permission to read, write, or execute

• copy2()
– Copyfile() + copystat
• copystat: metadata (permission + modification date, access date, etc.)

• copyfile < copy < copy2


Making a complete copy of a folder: copytree()

shutil_05.py
import shutil

sourceFolder = "abcPQR"
targetFolder = "New_abcPQR"
shutil.copytree(sourceFolder, targetFolder)
OS vs. Shutil (taken from Quora and Wikipedia)
• OS is largely thin wrappers around POSIX system calls and library functions.
– The Portable Operating System Interface (POSIX) is a family of standards specified by the IEEE
Computer Society for maintaining compatibility between operating systems.
• Shutil contains high-level Python-specific functions.
– These are built on top of Python’s os module and each call may represent dozens or hundreds of
calls to lower-level functions.
Lecture 11
OS and Shutil Modules
The End

You might also like