如何在 Python 中移动文件? [英] How to move a file in Python?

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

问题描述

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

<预><代码>>>>source_files = '/PATH/TO/FOLDER/*'>>>目的地文件夹 = '路径/目的地/文件夹'>>># 相当于 $ mv source_files destination_folder

解决方案

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

都使用相同的语法:

导入操作系统进口木材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.但是,如果目标与源位于不同的磁盘上,它将改为复制然后删除源文件.

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

解决方案

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

All employ the same syntax:

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

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.

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.

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.

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

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