本文實例主要實現Python中的文件復制操作,有兩種方法,具體實現代碼如下所示:
#coding:utf-8 # 方法1:使用read()和write()模擬實現文件拷貝 # 創建文件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模塊是一個文件、目錄的管理接口,提供了一些用于復制文件、目錄的函數 # copyfile()函數可以實現文件的拷貝 # copyfile(src, dst) # move()函數實現文件的剪切 # move(src, dst) import shutil shutil.copyfile("hello.py", "hello2.py") #hello.txt內容復制給hello2.txt shutil.move("hello.py", "../") #hello.txt復制到當前目錄的父目錄,然后刪除hello.txt shutil.move("hell2.txt", "hello3.txt") #hello2.txt移到當前目錄并命名為hello3.py, 然后刪除hello2.txt 總結
以上就是本文關于淺談Python實現2種文件復制的方法的全部內容,希望對大家有所幫助。感興趣的朋友可以繼續參閱本站其他相關專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!
新聞熱點
疑難解答