欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python中移動文件的實現(xiàn)方法匯總

 更新時間:2025年07月17日 10:10:15   作者:1010n111  
在Python編程中,經(jīng)常會遇到需要移動文件的場景,例如文件的整理、備份等,這就需要借助Python的相關(guān)庫和方法來實現(xiàn)類似mv命令的功能,本文給大家匯總了Python移動文件的實現(xiàn)方法,需要的朋友可以參考下

Python中移動文件的方法

實現(xiàn)步驟

使用os.rename()或os.replace()

這兩個函數(shù)都可以用于重命名或移動文件。使用時,需要確保目標目錄已經(jīng)存在。在Windows系統(tǒng)中,如果目標文件已存在,os.rename()會拋出異常,而os.replace()會直接替換該文件。

import os

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

shutil.move()是最接近Unixmv命令的方法。它在大多數(shù)情況下會調(diào)用os.rename(),但如果源文件和目標文件位于不同的磁盤上,它會先復制文件,然后刪除源文件。

import shutil

shutil.move("path/to/current/file.foo", "path/to/new/destination/for/file.foo")

使用pathlib.Path.rename()

在Python 3.4及以后的版本中,可以使用pathlib庫的Path類來移動文件。

from pathlib import Path

Path("path/to/current/file.foo").rename("path/to/new/destination/for/file.foo")

核心代碼

批量移動文件

import os
import shutil

path = "/volume1/Users/Transfer/"
moveto = "/volume1/Users/Drive_Transfer/"
files = os.listdir(path)
files.sort()
for f in files:
    src = path + f
    dst = moveto + f
    shutil.move(src, dst)

封裝為函數(shù)

import os
import shutil
import pathlib
import fnmatch

def move_dir(src: str, dst: str, pattern: str = '*'):
    if not os.path.isdir(dst):
        pathlib.Path(dst).mkdir(parents=True, exist_ok=True)
    for f in fnmatch.filter(os.listdir(src), pattern):
        shutil.move(os.path.join(src, f), os.path.join(dst, f))

最佳實踐

  • 當不確定源文件和目標文件是否在同一設備上時,建議使用shutil.move()。
  • 使用os.path.join()來拼接文件路徑,以避免跨平臺問題。
  • 如果需要處理文件的元數(shù)據(jù),要注意shutil.copy2()可能無法復制所有元數(shù)據(jù)。

常見問題

  • os.rename()無法處理跨設備文件移動:如果源文件和目標文件位于不同的磁盤上,os.rename()會拋出異常,此時應使用shutil.move()。
  • 目標文件已存在:在Windows系統(tǒng)中,os.rename()會拋出異常,而os.replace()會直接替換該文件。使用shutil.move()時,在某些Python版本中也可能會出現(xiàn)問題,需要手動處理。
  • 使用~路徑~是shell的構(gòu)造,Python中應使用os.getenv('HOME')os.path.expanduser()來處理。

到此這篇關(guān)于Python中移動文件的實現(xiàn)方法匯總的文章就介紹到這了,更多相關(guān)Python移動文件方法內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論