码迷,mamicode.com
首页 > 编程语言 > 详细

python操作文件

时间:2018-08-10 11:41:17      阅读:188      评论:0      收藏:0      [点我收藏+]

标签:tool   mes   就会   names   ras   end   复制   xxxxx   pen   

读写

可以使用w,a,r,wb,ab,rb等模式

with open('xxx.xx', 'wb') as f:
    f.write('xxxxxxxxx')

复制

如果destination是文件夹,source文件将复制到destination中,并保持原来的文件名

如果destination是文件名结尾,它将作为被复制文件的新名字

shutil.copy(source, destination)

移动

如果destination是文件夹,source 文件将移动到destination中,并保持原来的文件名

如果destination文件夹中已存在source这个文件,destination文件夹中的同名文件将被覆盖

如果没有destination文件夹,就会将source改名为destination

shutil.move(source, destination)

删除

os.unlink(file)删除file文件(单个文件)

os.rmdir(path)删除path文件夹,该文件夹必须为空,其中没有任何文件和子文件夹(单个空文件夹)

shutil.rmtree(path)删除path文件夹,它包含的所有文件和子文件夹都会被删除

send2trash.send2trash(file)将文件夹和文件发送到计算机的垃圾箱或回收站,而不是永久删除它们

os.walk()函数被传入一个字符串值,即一个文件夹的路径。你可以在一个 for

os.walk()遍历目录树,返回 3 个值:

1.当前遍历的文件夹名称;

2.当前文件夹中子文件夹列表;

3.当前文件夹中文件列表。

压缩

# 新建压缩文件以写模式打开,写模式将擦除ZIP文件中所有原有的内容

# 第二个参数传入'a'则以添加模式打开,将文件添加到原有的 ZIP 文件中,

>>> newZip = zipfile.ZipFile('new.zip', 'w')

# write()方法第一个参数传入文件,就会压缩该文件,将它加到ZIP文件中,第二个参数是“压缩类型”,告诉计算机使用怎样的算法来压缩文件

>>> newZip.write('spam.txt', compress_type=zipfile.ZIP_DEFLATED)

>>> newZip.close()

打开压缩文件

>>> exampleZip = zipfile.ZipFile('example.zip')

# 查看压缩文件中所有文件和文件夹的列表

>>> exampleZip.namelist()

['spam.txt', 'cats/', 'cats/catnames.txt', 'cats/zophie.jpg']

# 返回指定文件的ZipInfo对象,ZipInfo对象有自己的属性

>>> spamInfo = exampleZip.getinfo('spam.txt')

# 原来文件大小

>>> spamInfo.file_size

13908

# 压缩后文件大小

>>> spamInfo.compress_size

3828

>>> 'Compressed file is %sx smaller!' % (round(spamInfo.file_size / spamInfo.compress_size, 2))

'Compressed file is 3.63x smaller!'

>>> exampleZip.close()

解压

# extractall()从ZIP文件中解压所有文件和文件夹,放到当前工作目录中

>>> exampleZip = zipfile.ZipFile('example.zip')

>>> exampleZip.extractall()

# 向extractall()传递文件夹名称,文件将解压到指定目录

>>> exampleZip.extractall('C:\\ delicious')

>>> exampleZip.close()

# extract()从ZIP文件中解压单个文件,第二个参数是解压到指定目录,如果指定文件夹不存在,会自动创建

>>> exampleZip.extract('spam.txt')

'C:\\spam.txt'

>>> exampleZip.extract('spam.txt', 'C:\\some\\new\\folders')

'C:\\some\\new\\folders\\spam.txt'

>>> exampleZip.close()


python操作文件

标签:tool   mes   就会   names   ras   end   复制   xxxxx   pen   

原文地址:http://blog.51cto.com/wenguonideshou/2157039

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!