Python에서 pathlib를 사용하여 파일 복사하기
Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.
Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.
아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.
Copy file with pathlib in Python
Python에서 pathlib를 사용하여 파일 복사하기
문제 내용
I try to copy a file with pathlib
저는 pathlib를 사용해 파일을 복사하려고 시도했습니다.
import pathlib
import shutil
my_file=pathlib.Path('/etc/hosts')
to_file=pathlib.Path('/tmp/foo')
shutil.copy(my_file, to_file)
I get this exception:
다음 예외가 발생합니다:
/home/foo_egs_d/bin/python /home/foo_egs_d/src/test-pathlib-copy.py
Traceback (most recent call last):
File "/home/foo_egs_d/src/test-pathlib-copy.py", line 6, in <module>
shutil.copy(my_file, to_file)
File "/usr/lib/python2.7/shutil.py", line 117, in copy
if os.path.isdir(dst):
File "/home/foo_egs_d/lib/python2.7/genericpath.py", line 41, in isdir
st = os.stat(s)
TypeError: coercing to Unicode: need string or buffer, PosixPath found
Process finished with exit code
... how to copy file with pathlib in Python 2.7?
... Python 2.7에서 pathlib로 파일을 복사하는 방법은 무엇입니까?
높은 점수를 받은 Solution
To use shutil.copy
:
shutil.copy를 사용하려면 다음과 같이 하면 됩니다:
import pathlib
import shutil
my_file = pathlib.Path('/etc/hosts')
to_file = pathlib.Path('/tmp/foo')
shutil.copy(str(my_file), str(to_file)) # For Python <= 3.7.
shutil.copy(my_file, to_file) # For Python 3.8+.
The problem is pathlib.Path
create a PosixPath
object if you're using Unix/Linux, WindowsPath
if you're using Microsoft Windows.
문제는 `pathlib.Path`가 Unix/Linux에서는 `PosixPath` 객체를, Microsoft Windows에서는 `WindowsPath` 객체를 생성한다는 것입니다.
With older versions of Python, shutil.copy
requires a string as its arguments. For them, use the str
function here.
이전 버전의 Python에서는 `shutil.copy`가 인자로 문자열을 요구합니다. 따라서 문자열 함수 `str`을 여기서 사용해야 합니다.
가장 최근 달린 Solution
You might use pathlib3x - it offers a backport of the latest (at the date of writing this answer Python 3.11.a0) Python pathlib for Python 3.6 or newer, and a few additional functions like copy
, copy2
, etc ...
pathlib3x를 사용해 볼 수 있습니다. 이것은 Python 3.6 이상에서 최신 (이 답변 작성 시점에서는 Python 3.11.a0) Python pathlib의 백포트를 제공하며, copy, copy2 등 몇 가지 추가 기능을 제공합니다.
$> python -m pip install pathlib3x
$> python
>>> import pathlib3x as pathlib
>>> my_file = pathlib.Path('/etc/hosts')
>>> to_file = pathlib.Path('/tmp/foo')
>>> my_file.copy(to_file)
you can find it on github or PyPi
github나 PyPI에서 해당 패키지를 찾을 수 있습니다.
Disclaimer: I'm the author of the pathlib3x library.
고지사항: 저는 pathlib3x 라이브러리의 저자입니다.
출처 : https://stackoverflow.com/questions/33625931/copy-file-with-pathlib-in-python