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

Python中移動(dòng)文件的實(shí)現(xiàn)方法匯總

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

Python中移動(dòng)文件的方法

實(shí)現(xiàn)步驟

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

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

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ù)情況下會(huì)調(diào)用os.rename(),但如果源文件和目標(biāo)文件位于不同的磁盤上,它會(huì)先復(fù)制文件,然后刪除源文件。

import shutil

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

使用pathlib.Path.rename()

在Python 3.4及以后的版本中,可以使用pathlib庫(kù)的Path類來(lái)移動(dòng)文件。

from pathlib import Path

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

核心代碼

批量移動(dòng)文件

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

最佳實(shí)踐

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

常見問題

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

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

相關(guān)文章

最新評(píng)論