我怎么能在Python中做mv src/* dest/的等效?
>>> source_files = '/PATH/TO/FOLDER/*'
>>> destination_folder = 'PATH/TO/FOLDER'
>>> # equivalent of $ mv source_files destination_folder
我怎么能在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更改为另一个命令。
其他回答
这是解决方案,它不启用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)
公认的答案并不是正确的答案,因为这个问题不是关于将一个文件重命名为一个文件,而是将许多文件移动到一个目录中。shutil。动起就动起,但为了这个目的。重命名是无用的(如注释中所述),因为目标必须有显式的文件名。
因为你不关心返回值,你可以这样做
import os
os.system("mv src/* dest/")
也可以使用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