本文實(shí)例主要實(shí)現(xiàn)Python中的文件復(fù)制操作,有兩種方法,具體實(shí)現(xiàn)代碼如下所示:
#coding:utf-8 # 方法1:使用read()和write()模擬實(shí)現(xiàn)文件拷貝 # 創(chuàng)建文件hello.txt src = file("hello.txt", "w") li = ["Hello world /n", "Hello China /n"] src.writelines(li) src.close() #把hello.txt 拷貝到hello2.txt src = file("hello.txt", "r") dst = file("hello2.txt", "w") dst.write(src.read()) src.close() dst.close() # 方法2:使用shutil模塊 # shutil模塊是一個(gè)文件、目錄的管理接口,提供了一些用于復(fù)制文件、目錄的函數(shù) # copyfile()函數(shù)可以實(shí)現(xiàn)文件的拷貝 # copyfile(src, dst) # move()函數(shù)實(shí)現(xiàn)文件的剪切 # move(src, dst) import shutil shutil.copyfile("hello.py", "hello2.py") #hello.txt內(nèi)容復(fù)制給hello2.txt shutil.move("hello.py", "../") #hello.txt復(fù)制到當(dāng)前目錄的父目錄,然后刪除hello.txt shutil.move("hell2.txt", "hello3.txt") #hello2.txt移到當(dāng)前目錄并命名為hello3.py, 然后刪除hello2.txt 總結(jié)
以上就是本文關(guān)于淺談Python實(shí)現(xiàn)2種文件復(fù)制的方法的全部?jī)?nèi)容,希望對(duì)大家有所幫助。感興趣的朋友可以繼續(xù)參閱本站其他相關(guān)專題,如有不足之處,歡迎留言指出。感謝朋友們對(duì)本站的支持!
新聞熱點(diǎn)
疑難解答
圖片精選