如何在 Python 中移动文件?

问题描述 投票:0回答:11

我怎样才能在 Python 中做相当于

mv
的事情?

mv "path/to/current/file.foo" "path/to/new/destination/for/file.foo"
python file file-handling python-os
11个回答
2048
投票

os.rename()
os.replace()
shutil.move()

全部采用相同的语法:

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")
  • 文件名 (
    "file.foo"
    ) 必须包含在源和目标参数中。如果两者不同,文件将被重命名和移动。
  • 创建新文件的目录必须已经存在。
  • 在 Windows 上,具有该名称的文件不得存在,否则将引发异常,但
    os.replace()
    即使在这种情况下也会默默地替换文件。
  • shutil.move
    在大多数情况下简单地调用
    os.rename
    。但是,如果目标与源位于不同的磁盘上,它将复制然后删除源文件。

324
投票

虽然

os.rename()
shutil.move()
都会重命名文件,但最接近Unix mv命令的命令是
shutil.move()
。不同之处在于,如果源和目标位于不同的磁盘上,则
os.rename()
不起作用,而
shutil.move()
是文件磁盘不可知论者。


119
投票

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


44
投票

对于

os.rename
shutil.move
您将需要导入模块。 移动所有文件不需要
*
字符。

我们在

/opt/awesome
有一个名为 source 的文件夹,其中有一个名为 awesome.txt 的文件。

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
看到文件夹名称实际上改变了。 这是
shutil
将目的地移回源头。

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

这次我检查了源文件夹以确保我创建的

awesome.txt
文件存在。在那里

现在我们已经将文件夹及其文件从源移动到目标,然后又移动回来。


31
投票

这是我目前正在使用的:

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))

16
投票

接受的答案不是正确的,因为问题不是关于将文件重命名为文件,而是将许多文件移动到目录中。

shutil.move
将完成这项工作,但为此目的
os.rename
是无用的(如评论所述),因为目标必须有一个明确的文件名。


4
投票

既然你不关心返回值,你可以这样做

import os
os.system("mv src/* dest/")

3
投票

也可以使用

subprocess.run()
方法。

python:
>>> import subprocess
>>> new = "/path/to/destination"
>>> old = "/path/to/new/destination"
>>> process = "mv ..{} ..{}".format(old,new)
>>> subprocess.run(process, shell=True) # do not remember, assign shell value to True.

这在 Linux 上工作时会很好。 Windows 可能会出错,因为没有 mv 命令。


2
投票

根据此处描述的答案,使用

subprocess
是另一种选择。

像这样的东西:

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

我很想知道与

shutil
相比,这种方法的优缺点。因为在我的情况下,我已经出于其他原因使用
subprocess
并且它似乎有效我倾向于坚持下去。

这取决于您运行脚本的 shell。

mv
命令适用于大多数 Linux shell(bash、sh 等),但也适用于 Windows 上的 Git Bash 等终端。对于其他终端,您必须将
mv
更改为备用命令。


0
投票

这是解决方案,它不能使用

shell
启用
mv

from subprocess import Popen, PIPE, STDOUT

source = "path/to/current/file.foo", 
destination = "path/to/new/destination/for/file.foo"

p = Popen(["mv", "-v", source, destination], stdout=PIPE, stderr=STDOUT)
output, _ = p.communicate()
output = output.strip().decode("utf-8")
if p.returncode:
    print(f"E: {output}")
else:
    print(output)

-1
投票
  import os,shutil

  current_path = "" ## source path

  new_path = "" ## destination path

  os.chdir(current_path)

  for files in os.listdir():

        os.rename(files, new_path+'{}'.format(f))
        shutil.move(files, new_path+'{}'.format(f)) ## to move files from 

不同的磁盘前。 C: --> D:

© www.soinside.com 2019 - 2024. All rights reserved.