您的位置:首页 > 编程语言 > Python开发

Python学习笔记(六)——组织文件

2018-02-06 17:52 399 查看

shutil模块

在Python程序中复制移动改名和删除文件

复制文件和文件夹

>>> shutil.copy('def.py','.\\test')
'.\\test\\def.py'
>>> os.listdir('.\\test')
['def.py']


在复制的时候为新复制的文件命名

>>> shutil.copy('def.py','.\\test\\def2.py')
'.\\test\\def2.py'
>>> os.listdir('.\\test')
['def.py', 'def2.py']


文件和文件夹的移动和改名

移动

>>> shutil.move('temp.txt','.\\test')
'.\\test\\temp.txt'


改名

>>> shutil.move('.\\test\\temp.txt','.\\test\\temp2.txt')
'.\\test\\temp2.txt'


构成目的地的文件夹必须已经存在

永久删除文件或文件夹

>>> os.makedirs('.\\test\\001')
>>> os.rmdir('.\\test\\001')  #删除001文件夹(文件夹中没有内容)
>>> os.unlink('.\\test\\def2.py') #删除文件def2.py
>>> os.makedirs('.\\test\\001')
>>> shutil.copy('.\\def.py','.\\test\\001')
'.\\test\\001\\def.py'
>>> os.rmdir('.\\test\\001')     #当文件夹中有文件的时候,os.rmdir()将会报错
Traceback (most recent call last):
File "<pyshell#17>", line 1, in <module>
os.rmdir('.\\test\\001')
OSError: [WinError 145] 目录不是空的。: '.\\test\\001'
>>> shutil.rmtree('.\\test\\001')    #使用shutil.rmtree()进行递归删除


用send2trash模块安全的删除

所谓安全的删除,及将要删除的文件放入回收站

>>> import send2trash
>>> send2trash.send2trash('.\\test\\temp2.txt')


判断是是文件还是文件夹

import os
if os.path.isdir(path):
print "it's a directory"
elif os.path.isfile(path):
print "it's a normal file"
else:
print "it's a special file (socket, FIFO, device file)"


遍历目录树

>>> for folder,subfolders,files in os.walk('.'):
print('  '*len(folder.split('\\'))+os.path.basename(folder))
for subfolder in subfolders:
print('  '*len(folder.split('\\'))+subfolder)
for file in files:
print('  '*len(folder.split('\\'))+file)


import os
for folder,subfolders,files in os.walk('D:\\python'):
print('当前文件夹:'+folder)
for subfolder in subfolders:
print('子文件夹有:'+folder+'\\'+subfolder)
for file in files:
print('下面的文件:'+folder+'\\'+file)
print('\n')
======================= RESTART: D:\python\os-walk.py =======================
当前文件夹:D:\python
子文件夹有:D:\python\test
下面的文件:D:\python\def.py

当前文件夹:D:\python\test
下面的文件:D:\python\test\def.py
下面的文件:D:\python\test\randomQuizGenerator.py


使用zipfile模块压缩文件

读取zip文件

>>> exampleZip = zipfile.ZipFile('test\\test.zip')
>>> exampleZip.namelist()
['randomQuizGenerator.py', 'def.py']
>>> spamInfo = exampleZip.getinfo('def.py')
>>> spamInfo.file_size
149
>>> spamInfo.compress_size
94
>>> '压缩率为 %s' % (round((spamInfo.file_size-spamInfo.compress_size)/spamInfo.fil
4000
e_size,2)*100)+'%'
'压缩率为 37.0%'
>>> exampleZip.close()


从zip文件中解压缩

解压时支持创建文件夹

>>> exampleZip = zipfile.ZipFile('test.zip')
>>> exampleZip.extractall('.\\temp')     #默认当前文件夹
>>> exampleZip.extractall('.\\temp2\\temp3\\temp4')


可以指定zip内部文件进行解压

>>> exampleZip.extract('def.py')
'D:\\python\\test\\def.py'
>>> exampleZip.extract('def.py','.\\temp')
'temp\\def.py'


创建和添加ZIP文件

>>> os.getcwd()
'D:\\python\\test\\temp'
>>> newZip = zipfile.ZipFile('new.zip','w')
#这里的‘w’和使用open()函数时类似,也可以用‘a’
>>> newZip.write('def.py',compress_type=zipfile.ZIP_DEFLATED)
>>> newZip.close()


小实验——将带有美国风格日期的文件改名为欧洲风格

注:
(.*?)
怎么理解?

点 是任意字符

* 是取 0 至 无限长度

问号 是非贪婪模式。

何在一起就是 取尽量少的任意字符,一般不会这么单独写,他大多用在:

.*?a

就是取前面任意长度的字符,到底一个 a 出现,匹配如下

q@wer_qwerqweraljlkjlkjlkj

得到:q@wer_qwerqwera 这部分,如果匹配不到后面的 a 字符,则匹配为空。

#!python3
#renameDates.py - Rename filenames with American MM-DD-YYYY date format to European DD-MM-YYYY

import os,shutil,re
#为美国风格的日期建立一个正则表达式
date = re.compile(r'''
^(.*?)
((0|1)?\d)-
((0|1|2|3)?\d)-
((19|20)\d\d)
(.*?)$
''',re.VERBOSE)
#Loop over the file in the working directory.
for filename in os.listdir('.'):
mo = date.search(filename)
#Skip files without date.
if mo == None:
continue
#Get the different parts od the filename.
beforPart = mo.group(1)
monthPart = mo.group(2)
dayPart = mo.group(4)
yearPart = mo.group(6)
afterPart = mo.group(8)
"""
date = re.compile(r'''
^(1)
(2(3))-
(4(5))-
(6(7))
(8)$
''',re.VERBOSE)
"""
#Form the European-style filename.
euroDate = beforPart + dayPart +'-'+ monthPart +'-'+ yearPart + afterPart

#Get the full,absolute file paths
absPath = os.path.abspath('.')
amerPath = os.path.join(absPath,filename)
EuroPath = os.path.join(absPath,euroDate)

#Rename the file.
print('Rename %s to %s'%(amerPath,EuroPath))
shutil.move(amerPath,EuroPath)


小实验——将一个文件夹备份到一个zip文件

#! python3
#backupToZip.py - Copies an entire folder and its contents into a ZIP file whose filename increments.
#Usage:backupToZip.py <Path> - Compress the file of the abspath to a backup.

#Author : qmeng
#MailTo : qmeng1128@163.com
#QQ     : 1163306125
#Blog   : http://blog.csdn.net/Mq_Go/ #Create : 2018-02-07
#Version: 1.0

import sys,zipfile,os
def backupfile(folder):
#Backup the entire contents of "folder" into a zip file
if os.path.isabs(folder) != True:
folder = os.path.abspath(folder)
number = 1
while True:
zipName = os.path.basename(folder) + '_' + str(number) + '.zip'
if not os.path.exists(os.path.join(os.path.dirname(folder),zipName)):
print(os.path.join(os.path.dirname(folder),zipName))
break
number = number + 1

# Create the zip file
print('Create the %s...'%(zipName))
backupZip = zipfile.ZipFile(os.path.join(os.path.dirname(folder),zipName),'w')

#Walk the entire folder tree and compress the files in each folder.
for folder,subfolders,files in os.walk(folder):
print('Add file is in %s...'%(folder))
backupZip.write(folder)
for file in files:
newBase = os.path.basename(folder)+'_'
if file.startswith(newBase) and file.endswith('.zip'):
continue
backupZip.write(os.path.join(folder,file))
backupZip.close()
print('Done')
if len(sys.argv) == 2:
if not os.path.exists(sys.argv[1].lower()):
print('No such file')
else:
backupfile(sys.argv[1].lower())


结果:

C:\Users\>backupToZip.py D:\\python\\test
d:\\python\test_2.zip
Create the test_2.zip...
Add file is in d:\\python\\test...
Add file is in d:\\python\\test\temp...
Done
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: