본문 바로가기
Development/Python

Python에서 directory 관련 명령어

by 곽동현 IMCOMKING 2020. 2. 19.

가장 간단한 형태의 glob을 이용 wild_card copy(recursive 보장 안됨)


import os
import glob
import shutil
def glob_copy(src, dst, name_pattern="*"):
if not os.path.exists(dst):
os.mkdir(dst)
shutil.copystat(src, dst)

including = glob.glob(os.path.join(src, name_pattern))
print("including:", including)
for file in os.listdir(src):
print("file:", file)
file = os.path.join(src, file)
if file in including and os.path.isfile(file):
shutil.copy(file, dst)


cp --parents 명령어 구현하기

def make_safe_dir(dir):
if not os.path.exists(dir):
os.makedirs(dir)


def remove_safe_dir(dir):
if os.path.isfile(dir) or os.path.exists(dir):
shutil.rmtree(dir)


def cp_parents(cwd, full_file_path, tmpdir):
dir_diff = full_file_path.replace(cwd, "").split("/")[1:-1]
file_name = full_file_path.split("/")[-1]
target_dir = ""
if len(dir_diff):
target_dir = os.path.join(*dir_diff)
make_safe_dir(os.path.join(tmpdir, target_dir))
shutil.copy(full_file_path, os.path.join(tmpdir, target_dir, file_name))


with tempfile.TemporaryDirectory() as tmpdir:
tmpdir = "../tmp_test"
make_safe_dir(tmpdir)
# Copy necessary deps
cwd = os.getcwd()
for file_wild_card in files:
for full_file_path in glob.glob(os.path.join(cwd, file_wild_card)):
cp_parents(cwd, full_file_path, tmpdir)


아래의 이슈를 보면, cp --parents를 구현하려는 시도들이 많이 있다. 위 코드는 내 나름대로 쉬운 방식으로 구현한 코드이다.

https://stackoverflow.com/questions/15329223/copy-a-file-into-a-directory-with-its-original-leading-directories-appended





std python library의 문제점을 개선한 Copytree 구현체

import os
import shutil
import stat
def copytree(src, dst, symlinks=False, ignore=None):
if not os.path.exists(dst):
os.makedirs(dst)
shutil.copystat(src, dst)
lst = os.listdir(src)
if ignore:
excl = ignore(src, lst)
lst = [x for x in lst if x not in excl]
for item in lst:
s = os.path.join(src, item)
d = os.path.join(dst, item)
if symlinks and os.path.islink(s):
if os.path.lexists(d):
os.remove(d)
os.symlink(os.readlink(s), d)
try:
st = os.lstat(s)
mode = stat.S_IMODE(st.st_mode)
os.lchmod(d, mode)
except:
pass # lchmod not available
elif os.path.isdir(s):
copytree(s, d, symlinks, ignore)
else:
shutil.copy2(s, d)




Symbolic link 만들기

os.symlink("modules", "dest/modules"), target_is_directory=True)


https://www.geeksforgeeks.org/python-os-symlink-method/#:~:text=symlink()%20method%20in%20Python,pointing%20to%20source%20named%20destination.




'Development > Python' 카테고리의 다른 글

Conda로 Python 버전 별 설치, 관리, 삭제하기  (0) 2020.02.27
Python Multiprocessing 가이드  (2) 2020.02.20
Python에서 directory 관련 명령어  (0) 2020.02.19
Python 코드 안에서 git과 pip 사용하기  (0) 2020.02.19
Advanced Python Scheduler  (0) 2020.02.18
Airflow  (0) 2020.02.11

댓글0