1、复制文件和文件夹,调用 shutil.copy()
>>> import shutil, os
>>> os.chdir('C:\')
>>> shutil.copy('C:\spam.txt', 'C:\delicious')
'C:\delicious\spam.txt'
>>> shutil.copy('eggs.txt', 'C:\delicious\eggs2.txt')
'C:\delicious\eggs2.txt'
2、shutil.move()方法可以改文件名
>>> import shutil
>>> shutil.move('C:\bacon.txt', 'C:\eggs')
'C:\eggs\bacon.txt'
>>> shutil.move('C:\bacon.txt', 'C:\eggs\new_bacon.txt')
'C:\eggs\new_bacon.txt'
3、shutil模块可以删除一个文件夹及其所有的内容。
import os
for filename in os.listdir():
if filename.endswith('.rxt'):
#os.unlink(filename)
print(filename)
以上就是python shutil模块操作文件的方法,希望对大家有所帮助。更多Python学习指路:python基础教程
本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。


