我怎么能在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
当前回答
这是解决方案,它不启用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)
其他回答
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:
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。在大多数情况下重命名。但是,如果目标文件位于与源文件不同的磁盘上,则会复制源文件,然后删除源文件。
根据这里描述的答案,使用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.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