Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
169 views
in Technique[技术] by (71.8m points)

python - 如何在Python中移动文件(How to move a file in Python)

I looked into the Python os interface, but was unable to locate a method to move a file. (我查看了Python的os界面,但无法找到移动文件的方法。) How would I do the equivalent of $ mv ... in Python? (我将如何在Python中做相当于$ mv ...工作?)

>>> source_files = '/PATH/TO/FOLDER/*'
>>> destination_folder = 'PATH/TO/FOLDER'
>>> # equivalent of $ mv source_files destination_folder
  ask by David542 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

All employ the same syntax: (全部采用相同的语法:)

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

Note that you must include the file name ( file.foo ) in both the source and destination arguments. (请注意,您必须在源和目标参数中都包含文件名( file.foo )。) 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. (在Windows上,必须不存在具有该名称的文件,否则将引发异常,但是os.replace()会静默替换该文件,即使在这种情况下也是如此。)

As has been noted in comments on other answers, shutil.move simply calls os.rename in most cases. (正如在其他答案的评论所指出, shutil.move简单的调用os.rename在大多数情况下。) However, if the destination is on a different disk than the source, it will instead copy and then delete the source file. (但是,如果目标与源位于不同的磁盘上,它将代替复制然后删除源文件。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...