How to move a file?

后端 未结 9 1863
夕颜
夕颜 2020-11-22 01:07

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?

&g         


        
9条回答
  •  鱼传尺愫
    2020-11-22 01:28

    os.rename(), shutil.move(), or 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. 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.

提交回复
热议问题