我怎么能在Python中做mv src/* dest/的等效?

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

当前回答

根据这里描述的答案,使用subprocess是另一种选择。

就像这样:

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

我很好奇,与shutil相比,这种方法的优点和缺点。因为在我的情况下,我已经使用subprocess的其他原因,它似乎工作,我倾向于坚持它。

这取决于运行脚本的shell。mv命令适用于大多数Linux shell (bash、sh等),但也适用于Windows上的Git bash等终端。对于其他终端,您必须将mv更改为另一个命令。

其他回答

根据这里描述的答案,使用subprocess是另一种选择。

就像这样:

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

我很好奇,与shutil相比,这种方法的优点和缺点。因为在我的情况下,我已经使用subprocess的其他原因,它似乎工作,我倾向于坚持它。

这取决于运行脚本的shell。mv命令适用于大多数Linux shell (bash、sh等),但也适用于Windows上的Git bash等终端。对于其他终端,您必须将mv更改为另一个命令。

  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:

也可以使用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命令。

在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

虽然os.rename()和shutil.move()都将重命名文件,但最接近Unix mv命令的命令是shutil.move()。不同之处在于,如果源文件和目标文件在不同的磁盘上,os.rename()将不起作用,而shutil.move()是文件与磁盘无关的。