티스토리 뷰
Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.
Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.
아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.
How to move a file in Python?
파이썬에서 파일 이동시키기
문제 내용
How would I do the equivalent of mv src/* dest/
in Python?
파이썬에서 mv src/* dest/ 와 동일한 기능을 수행하려면 어떻게 해야 합니까?
>>> source_files = '/PATH/TO/FOLDER/*'
>>> destination_folder = 'PATH/TO/FOLDER'
>>> # equivalent of $ mv source_files destination_folder
높은 점수를 받은 Solution
os.rename()
, os.replace()
, or shutil.move()
os.rename(), os.replace() 또는 shutil.move() 를 사용할 수 있습니다.
All employ the same syntax:
모두 동일한 구문을 사용합니다.
import os
import shutil
os.rename("path/to/current/file.foo", "path/to/new/destination/for/file.foo")
os.replace("path/to/current/file.foo", "path/to/new/destination/for/file.foo")
shutil.move("path/to/current/file.foo", "path/to/new/destination/for/file.foo")
Note that you must include the file name (file.foo
) in both the source and destination arguments. If it is changed, the file will be renamed as well as moved.
source 인수와 destination 인수 모두에 파일 이름(file.foo)을 포함해야 합니다. 변경되면 파일 이름이 바뀌고 이동됩니다.
Note also that in the first two cases the directory in which the new file is being created must already exist. On Windows, a file with that name must not exist or an exception will be raised, but os.replace()
will silently replace a file even in that occurrence.
또한 처음 두 경우에는 새 파일이 생성되는 디렉토리가 이미 존재해야 합니다. 윈도우즈에서는 해당 이름의 파일이 존재해서는 안 되며 예외가 발생하지만 os.replace()가 자동으로 파일을 대체합니다.
As has been noted in comments on other answers, shutil.move
simply calls os.rename
in most cases. However, if the destination is on a different disk than the source, it will instead copy and then delete the source file.
다른 답변에 대한 의견에서 언급했듯이 shutil.move는 대부분의 경우 단순히 os.rename을 호출합니다. 그러나 대상이 원본과 다른 디스크에 있는 경우 대신 원본 파일을 복사한 다음 삭제합니다.
가장 최근 달린 Solution
Since you don't care about the return value, you can do
리턴 값을 볼 필요가 없다면 아래와 같이 사용 가능합니다.
import os
os.system("mv src/* dest/")
출처 : https://stackoverflow.com/questions/8858008/how-to-move-a-file-in-python
'개발 > 파이썬' 카테고리의 다른 글
Visual Studio Code의 Pylint "unresolved import" 오류 수정 방법 (0) | 2022.12.03 |
---|---|
urllib 및 python을 통해 사진 다운로드 (0) | 2022.12.03 |
기존 파일에 내용 추가하기 (0) | 2022.12.03 |
장고 앱 이름 바꾸기 (0) | 2022.12.03 |
Dictionary에서 아이템(요소) 삭제 (0) | 2022.12.02 |