Python学习7-9.1-9.组织文件

本文详细介绍了使用Python进行文件操作的方法,包括复制、移动、删除文件及文件夹,遍历目录树,压缩与解压文件,以及如何通过正则表达式批量修改文件名中的日期格式。适用于希望提高文件管理效率的Python开发者。
部署运行你感兴趣的模型镜像


本文为学习python编程时所记录的笔记,仅供学习交流使用。

9.1 shutil模块

9.1.1 复制文件和文件夹

shutil.copy(source,destination)

>>> import shutil,os
>>> os.chdir('c:\\')
>>> shutil.copy('C:\\spam.txt','C:\\delicious')
0'C:\\delicious\\spam.txt'
>>> shutil.copy('eggs.txt','C:\\delicious\\eggs.txt')
'C:\\delicious\\eggs.txt'
>>> shutil.copy('eggs.txt','C:\\delicious\\eggs1.txt')
'C:\\delicious\\eggs1.txt'

shutil.copytree(source,destination)

>>> import shutil,os
>>> os.chdir('C:\\')
>>> shutil.copytree('C:\\delicious','C:\\delicious_backup')
'C:\\delicious_backup'

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

shutil.move(source,destination)

>>> import shutil
>>> shutil.move('C:\\delicious\\spam.txt','C:\\ddd')
'C:\\ddd\\spam.txt'
>>> shutil.move('C:\\delicious\\eggs.txt','C:\\ddd\\eggsupdated.txt')
'C:\\ddd\\eggsupdated.txt'

9.1.3 永久删除文件和文件夹

>>> import shutil,os
>>> os.chdir('C:\\ddd')
>>> for filename in os.listdir():
	if filename.endswith('.txt'):
		os.unlink(filename)
		print(filename)

		
eggsupdated.txt
spam.txt

9.1.4 用send2trash模块安全地删除

>>> import send2trash
>>> baconFile=open('bacon.txt','a') #creates the file
>>> baconFile.write('Bacon is not a vegetable.')
25
>>> baconFile.close()
>>> send2trash.send2trash('bacon.txt')

9.2 遍历目录树

>>> for folderName,subfolders,filenames in os.walk('C:\\delicious'):
	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('')

	
The current folder isC:\delicious
SUBFOLDER OF C:\delicious:456
SUBFOLDER OF C:\delicious:walnut
FILE INSIDEC:\delicious:eggsupdated.txt

The current folder isC:\delicious\456

The current folder isC:\delicious\walnut
SUBFOLDER OF C:\delicious\walnut:waffles

The current folder isC:\delicious\walnut\waffles
FILE INSIDEC:\delicious\walnut\waffles:eggsupdated.txt
FILE INSIDEC:\delicious\walnut\waffles:spam.txt


9.3 用zipfile模块压缩文件

9.3.1 读取zip文件

调用zipfile.ZipFile()函数实现

>>> import zipfile,os
>>> os.chdir('C:\\')#move to the folder with examples.zip
>>> exampleZip=zipfile.ZipFile('examples.zip')
>>> exampleZip.namelist()
['cats/catnames.txt', 'cats/unknowncats.jpg', 'spma.txt']
>>> spamInfo=exampleZip.getinfo('spma.txt')
>>> spamInfo.file_size
6
>>> spamInfo.compress_size
6
>>> 'Compressed file is %sx smaller'%(round(spamInfo.file_size/spamInfo.compress_size,2))
'Compressed file is 1.0x smaller'
>>> exampleZip.close()

9.3.2 从zip文件中解压缩

>>> import zipfile,os
>>> os.chdir('C:\\')#move to the folder with examples.zip
>>> exampleZip=zipfile.ZipFile('examples.zip')
>>> exampleZip.extractall('C:\\delicious')
>>> exampleZip.close()
>>> exampleZip=zipfile.ZipFile('examples.zip')
>>> exampleZip.extract('spma.txt','C:\\some\\new\\folders')
'C:\\some\\new\\folders\\spma.txt'
>>> exampleZip.close()

9.3.3 创建和添加到zip文件

>>> import zipfile
>>> os.chdir('C:\\Users\\VECTOR\\AppData\\Local\\Programs\\Python\\Python37\\Scripts')
>>> newZip=zipfile.ZipFile('new.zip','w')
>>> newZip.write('C:\\some\\new\\folders\\spma.txt',compress_type=zipfile.ZIP_DEFLATED)
>>> newZip.close()

9.4 将带有美国风格的日期的文件名改名为欧洲风格日期

美国风格日期 MM-DD-YYYY
欧洲风格日期 DD-MM-YYYY

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

import shutil,os,re

# Create a regex that matches file with the Amercian date format.
datePattern=re.compile(r"""^(.*?) #all text before the date
    ((0|1)?\d)-   #one or two digits for the month
    ((0|1|2|3)?\d)- # one or two digits for the day
    ((19|20)\d\d) #four digits for the year
    (.*?)$ #all text after the date
    """,re.VERBOSE)


#TODO: Loop over the files in the working directory
for amerFilename in os.listdir('.'):
    mo=datePattern.search(amerFilename)
    
#TODO: Skip files without a date.
    if mo==None:
        continue

#TODO: Get the different parts of the filename.
    beforePart=mo.group(1)
    monthPart=mo.group(2)
    dayPart=mo.group(4)
    yearPart=mo.group(6)
    afterPart=mo.group(8)

#TODO: Form the European-style filename
    euroFilename=beforePart+dayPart+'-'+monthPart+'-'+yearPart+afterPart
#TODO: Get the full,absolute file path
    absWorkingDir=os.path.abspath('.')
    amerFilename=os.path.join(absWorkingDir,amerFilename)
    euroFilename=os.path.join(absWorkingDir,euroFilename)
#TODO: Rename the files.
    print('Renaming "%s" to "%s"...'%(amerFilename,euroFilename))
    #shutil.move(amerFilename,euroFilename) #uncomment after testing



内容来源

[1] [美]斯维加特(Al Sweigart).Python编程快速上手——让繁琐工作自动化[M]. 王海鹏译.北京:人民邮电出版社,2016.7.p157-172

您可能感兴趣的与本文相关的镜像

Python3.10

Python3.10

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值