如何移动文件? [英] How to move a file?

查看:80
本文介绍了如何移动文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我查看了Python os 界面,但无法找到移动文件的方法.我将如何在Python中执行$ mv ...的等效功能?

I looked into the Python os interface, but was unable to locate a method to move a file. How would I do the equivalent of $ mv ... in Python?

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

推荐答案

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).如果更改,文件将被重命名并移动.

Note that you must include the file name (file.foo) in both the source and destination arguments. If it is changed, the file will be renamed as well as moved.

还请注意,在前两种情况下,用于创建新文件的目录必须已经存在.在Windows上,必须不存在具有该名称的文件,否则会引发异常,但是os.replace()会在出现这种情况时以静默方式替换文件.

Note also that in the first two cases the directory in which the new file is being created must already exist. On Windows, a file with that name must not exist or an exception will be raised, but os.replace() will silently replace a file even in that occurrence.

正如在对其他答案的评论中所指出的那样,shutil.move在大多数情况下仅调用os.rename.但是,如果目标与源位于不同的磁盘上,它将复制然后删除源文件.

As has been noted in comments on other answers, shutil.move simply calls os.rename in most cases. However, if the destination is on a different disk than the source, it will instead copy and then delete the source file.

这篇关于如何移动文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆