[python] 파일을 옮기는 방법?

Python os인터페이스를 살펴 보았지만 파일을 이동하는 메소드를 찾을 수 없습니다. $ mv ...파이썬에서 어떻게 동등 합니까?

>>> source_files = '/PATH/TO/FOLDER/*'
>>> destination_folder = 'PATH/TO/FOLDER'
>>> # equivalent of $ mv source_files destination_folder



답변

os.rename(), shutil.move()또는os.replace()

모두 동일한 구문을 사용합니다.

import os
import shutil

os.rename("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")
os.replace("path/to/current/file.foo", "path/to/new/destination/for/file.foo")

file.foo소스 및 대상 인수 모두에 파일 이름 ( )을 포함해야합니다 . 변경되면 파일 이름이 바뀌고 이동됩니다.

또한 처음 두 경우에는 새 파일이 작성되는 디렉토리가 이미 존재해야합니다. Windows에서는 해당 이름의 파일이 존재하지 않아야합니다. 그렇지 않으면 예외가 발생하지만 os.replace()해당 경우에도 파일이 자동으로 대체됩니다.

다른 답변에 대한 의견에서 언급했듯이 대부분의 경우 shutil.move전화하십시오 os.rename. 그러나 대상이 원본과 다른 디스크에 있으면 원본 파일을 복사 한 다음 삭제합니다.


답변

비록 os.rename()shutil.move()두 이름 바꾸기 파일 것, 유닉스 MV 명령에 가장 가까운 명령이다 shutil.move(). 차이점은 os.rename()소스와 대상이 다른 디스크에 있으면 shutil.move()작동하지 않지만 파일이있는 디스크는 신경 쓰지 않는다는 것입니다.


답변

os.rename 또는 shutil.move의 경우 모듈을 가져와야합니다. 모든 파일을 이동시키기 위해 * 문자가 필요하지 않습니다.

/ opt / awesome에 awesome.txt라는 하나의 파일이있는 source라는 폴더가 있습니다.

in /opt/awesome
  ls
source
  ls source
awesome.txt

python
>>> source = '/opt/awesome/source'
>>> destination = '/opt/awesome/destination'
>>> import os
>>> os.rename(source, destination)
>>> os.listdir('/opt/awesome')
['destination']

os.listdir을 사용하여 실제로 폴더 이름이 변경되었음을 확인했습니다. 목적지는 소스로 다시 이동하는 셔틀입니다.

>>> import shutil
>>> shutil.move(destination, source)
>>> os.listdir('/opt/awesome/source')
['awesome.txt']

이번에는 소스 폴더 내부에서 내가 만든 awesome.txt 파일이 있는지 확인했습니다. 저기있어 🙂

이제 폴더와 파일을 소스에서 대상으로 이동했다가 다시 되돌 렸습니다.


답변

Python 3.4 이후에는 pathlib의 클래스 Path를 사용 하여 파일을 이동할 수도 있습니다.

from pathlib import Path

Path("path/to/current/file.foo").rename("path/to/new/destination/for/file.foo")

https://docs.python.org/3.4/library/pathlib.html#pathlib.Path.rename


답변

이것이 현재 사용중인 것입니다.

import os, shutil
path = "/volume1/Users/Transfer/"
moveto = "/volume1/Users/Drive_Transfer/"
files = os.listdir(path)
files.sort()
for f in files:
    src = path+f
    dst = moveto+f
    shutil.move(src,dst)

이제 완벽하게 작동합니다. 이것이 도움이되기를 바랍니다.

편집하다:

나는 이것을 소스와 대상 디렉토리를 받아 들여 존재하지 않는 경우 대상 폴더를 만들고 파일을 이동시키는 함수로 바꿨다. 예를 들어 이미지 만 이동하려는 경우 src 파일을 필터링 할 수 있습니다. '*.jpg'기본적으로 패턴을 사용 하면 디렉토리의 모든 항목이 이동합니다

import os, shutil, pathlib, fnmatch

def move_dir(src: str, dst: str, pattern: str = '*'):
    if not os.path.isdir(dst):
        pathlib.Path(dst).mkdir(parents=True, exist_ok=True)
    for f in fnmatch.filter(os.listdir(src), pattern):
        shutil.move(os.path.join(src, f), os.path.join(dst, f))


답변

질문의 답은 파일 이름을 파일로 바꾸는 것이 아니라 많은 파일을 디렉토리로 옮기는 것에 대한 것이기 때문에 대답이 맞지 않습니다. 대상은 명시적인 파일 이름을 가져야하므로이 shutil.move작업을 수행하는 os.rename데는 주석에 명시된대로 쓸모가 없습니다.


답변

여기설명 된 답변에 따라 사용 subprocess하는 또 다른 옵션입니다.

이 같은:

subprocess.call("mv %s %s" % (source_files, destination_folder), shell=True)

에 비해이 방법의 장단점을 알고 싶습니다 shutil. 내 경우에는 이미 subprocess다른 이유로 사용하고 있으며 작동하는 것처럼 보입니다.

시스템에 따라 다릅니 까?