shutil模块
1.复制文件和文件夹
import shutil,os
os.chdir('d:\\devil')
shutil.copy('test.cpp','.\Dev-Cpp')
2.文件和文件夹的移动与改名
import shutil,os
shutil.move('test.cpp','.\Dev-Cpp')
shutil.move('test.cpp','.\Dev-Cpp\111.cpp')
3.永久删除文件和文件夹
- os.unlimk(path)删除path处的文件
- 调用os.rmdir(path)删除path处的文件夹 该文件夹必须为空 其中没有任何文件和文件夹
- shutil.rmtree(path)删除path的文件夹 包含所有文件和文件夹都被删除
可以第一次运行程序注释掉这些调用 并且加上print()调用 显示会被删除的文件
import os
for filename in os.listdir():
if filename.endswith('.rxt'):
os.unlink(filename)
4.用send2trash模块安全删除
import send2trash
bconFile = open('bacon.txt','a')
bconFile.write('This is a test!')
bconFile.close()
send2trash.send2trash('bacon.txt')
- send2trash 回收到垃圾箱 可以找回
遍历目录树
#! /usr/bin/python3
#! /usr/bin/python3
import os
for folderName,subfolders,filenames in os.walk('/datacode'):
print('The current folder is '+folderName)
for subfolder in subfolders:
print('SUBFOLDER OF ' +folderName+ ':' +subfolder)
for filename in filenames:
print('FILE INSIDE '+folderName+ ':'+filename)
print('')
==============
os.walk()函数传入返回三个值:
- 当前文件夹名称的字符串
- 当前文件夹中子文件夹的字符串列表
- 当前文件夹中文件的字符串的列表
当前文件夹值for循环当前迭代的文件夹 程序的当前工作目录 不会因为os.walk()而改变
通常使用foldername subfolders filenames来描述以上变量
******结果遍历***
The current folder is /datacode
SUBFOLDER OF /datacode:shiyanlou_cs427
The current folder is /datacode/shiyanlou_cs427
SUBFOLDER OF /datacode/shiyanlou_cs427:.git
FILE INSIDE /datacode/shiyanlou_cs427:wx_02_calculator.py
FILE INSIDE /datacode/shiyanlou_cs427:wx_03_2048.py
FILE INSIDE /datacode/shiyanlou_cs427:icon.ico
FILE INSIDE /datacode/shiyanlou_cs427:README.md
FILE INSIDE /datacode/shiyanlou_cs427:wx_01_polygon.py
FILE INSIDE /datacode/shiyanlou_cs427:wx_00_base.py
FILE INSIDE /datacode/shiyanlou_cs427:.gitignore
FILE INSIDE /datacode/shiyanlou_cs427:wx_00_line.py
...
os.walk返回字符串的列表 保存在subfolder和filename变量中
用zipfile模块压缩文件
- 读取ZIP文件
import zipfile,os
os.chdir('/datacode')
>>> exZip = zipfile.ZipFile('example.zip')
>>> exZip.namelist()
['example/', 'example/ccc/', 'example/cats.txt']
>>> spinfo = exZip.getinfo('example/cats.txt')
>>> spinfo.file_size
11525
>>> spinfo.compress_size
5169
>>> exZip.close()
- 从ZIP文件中解压缩
>>> exZip.extractall('/datacode')
[root@izwz9eitqs320brxl6owssz datacode]# ll
total 16
drwxr-xr-x 3 root root 4096 Aug 16 16:01 example
-rw-r--r-- 1 root root 5647 Aug 16 16:02 example.zip
drwxr-xr-x 3 root root 4096 Aug 16 11:16 shiyanlou_cs427
- 创建和添加到ZIP文件
wirte()方法传入一个路径 Python会压缩改路径所指的文件 加到ZIP文件中
write第一个参数是字符串 代表要添加的文件名 第二个参数是压缩类型参数
总是可以设置为zipfile.ZIP_DEFLATE(指定了defalte压缩算法)
>>> nzip = zipfile.ZipFile('newzip','w')
>>> nzip.write('example',compress_type=zipfile.ZIP_DEFLATED)
>>> nzip.close()
>>> exit()
[root@izwz9eitqs320brxl6owssz datacode]# ll
total 20
drwxr-xr-x 3 root root 4096 Aug 16 16:01 example
-rw-r--r-- 1 root root 5647 Aug 16 16:02 example.zip
-rw-r--r-- 1 root root 114 Aug 16 16:13 newzip
项目:将带有美国风格的文件改名为欧洲风格日期
#! /usr/bin/python3
import os,shutil,re
dateForm = r"""^(.*?)
((0|1)?\d)-
((0|1|2|3)?\d)-
((19|20)?\d\d)
(.*?)$
"""
datePattern = re.compile(dateForm,re.VERBOSE)
#Loop over the files in the working directory
for amerFile in os.listdir('.'):
mo = datePattern.search(amerFile)
if mo == None:
continue
#dateForm = r"""^(1)
# (2(3))-
# (4(5))-
# (6(7))
# (8)$
# """
beforepart = mo.group(1)
daypart = mo.group(2)
monthpart = mo.group(4)
yearpart = mo.group(6)
afterpart = mo.group(8)
#form the Euro-style filename.
eurofilename = beforepart + monthpart + '-' +daypart + '-' + yearpart +afterpart
absWorkingDir = os.path.abspath('.')
amerfilename = os.path.join(absWorkingDir,amerFile)
eurofilename = os.path.join(absWorkingDir,eurofilename)
#rename
print('Rename %s to %s.......') % (amerfilename,eurofilename)
#shutil.move(amerfilename,eurofilename)
项目:将一个文件夹备份到一个ZIP文件
description:文件保存在一个文件夹中 担心工作丢失 希望为整个文件夹创建一个ZIP文件 作为快照,希望保存不同的版本 例如 xx_1.zip xx_2.zip xx_3.zip 。
- 1.弄清楚ZIP文件的名称
- 2.创建新的ZIP文件
- 3.遍历目录树并添加到ZIP文件
#! /usr/bin/python3
"""
copies an entire folder and its contents into
a zip file whose filename increments.
"""
import zipfile,os
def backuptozip(folder):
folder = os.path.abspath(folder)
number = 1
while True:
zipFilename = os.path.basename(folder) +'_'+str(number)+'.zip'
if not os.path.exists(zipFilename):
break
number += 1
print('Creating %s ...' % (zipFilename))
backupzip = zipfile.ZipFile(zipFilename,'w')
print('Done!')
#p3 walk the entire folder tree and compress the files in each folder
for foldername,subfolder,filenames in os.walk(folder):
print('Adding files in %s ...' % (foldername))
backupzip.write(foldername)
#add all the files in this folder to the ZIP file
for filename in filenames:
newBase = os.path.basename(folder) + '_'
if filename.startswith(newBase) and filename.endswith('.zip'):
continue #dont backup the backup ZIP files
backupzip.write(os.path.join(foldername,filename))
backupzip.close()
print('Done.')
backuptozip('/datacode')