Examples of using Python to read and write and file compression and decompression core python tutorial

Python's os module provides basic file reading and writing method, and the compression operation zipfile module for compression and decompression of files, here we look at an example using Python to read and write and file compression and decompression:
read and write files
first look at a example:

f = open('thefile.txt','w')  #以写方式打开,
try:
  f.write('wokao')
finally:
  f.close()

Open the file:

f = open(‘文件','mode')
‘r':只读(缺省。如果文件不存在,则抛出错误)
‘w':只写(如果文件不存在,则自动创建文件),此时无法调用f.read()方法,且当调用f.write()时,将清空文件原有内容
‘a':附加到文件末尾
‘r+':读写

If you need to open the file in binary mode, you need to add back mode character "b", such as "rb", "wb", etc.

File attributes:

f.closed #标记文件是否已经关闭,由close()改写
f.encoding #文件编码
f.mode #打开模式
f.name #文件名
f.newlines #文件中用到的换行模式,是一个tuple
f.softspace #boolean型,一般为0,据说用于print

File read and write methods:

f.read([size]) #size为读取的长度,以byte为单位
f.readline([size]) #读一行,如果定义了size,有可能返回的只是一行的一部分
f.readlines([size]) #把文件每一行作为一个list的一个成员,并返回这个list。其实它的内部是通过循环调用readline()来实现的。如果提供size参数,size是表示读取内容的总长,也就是说可能只读到文件的一部分
f.write(str) #把str写到文件中,write()并不会在str后加上一个换行符
f.writelines(seq) #把seq的内容全部写到文件中。这个函数也只是忠实地写入,不会在每行后面加上任何东西
f.close() #关闭文件
f.flush() #把缓冲区的内容写入硬盘
f.fileno() #返回一个长整型的”文件标签“
f.isatty() #文件是否是一个终端设备文件(unix系统中的)
f.tell() #返回文件操作标记的当前位置,以文件的开头为原点
f.next() #返回下一行,并将文件操作标记位移到下一行。把一个file用于for … in file这样的语句时,就是调用next()函数来实现遍历的
f.seek(offset[,from]) #将文件打操作标记移到offset的位置。这个offset一般是相对于文件的开头来计算的,一般为正数。但如果提供了from参数就不一定了,from可以为0表示从头开始计算,1表示以当前位置为原点计算。2表示以文件末尾为原点进行计算。需要注意,如果文件以a或a+的模式打开,每次进行写操作时,文件操作标记会自动返回到文件末尾。
f.truncate([size]) #把文件裁成规定的大小,默认的是裁到当前文件操作标记的位置。

Python when reading a file, will remember its location in the file, if still need to re-read the second time, you need to call f.seek (0) re-reading from the beginning.

Some examples:

>>> f = open('hi.txt','w')
>>> f.closed
False
>>> f.mode
'w'
>>> f.name
'hi.txt'
>>> f.encoding

Compress and decompress files (zip / the unzip)
. 1, a single file into a zip file

#!/usr/bin/python
import zipfile
f = zipfile.ZipFile('archive.zip','w',zipfile.ZIP_DEFLATED)
f.write('1.py')
f.write('/root/install.log')
f.close()

After careful observation of compression archive.zip, which has a 1.py and a root directory, there is a install.log in the root directory
ZIP_DEFLATED is a compression flag, if it needs to be compiled using the zlib module, only if it is packaged without compression It can change zipfile.ZIP_STORED

2, the zip file

#!/usr/bin/python
import zipfile
zfile = zipfile.ZipFile('archive.zip','r')
for filename in zfile.namelist():
  data = zfile.read(filename)
  file = open(filename, 'w+b')
  file.write(data)
  file.close()

If there archive.zip directory, the corresponding directory should exist in the current directory, otherwise it will error.

3, the entire folder compression

#!/usr/bin/python
import zipfile
import os
f = zipfile.ZipFile('archive.zip','w',zipfile.ZIP_DEFLATED)
startdir = "c:\\\\mydirectory"
for dirpath, dirnames, filenames in os.walk(startdir):
  for filename in filenames:
    f.write(os.path.join(dirpath,filename))
f.close()

If there is:
Compression requires the (missing) zlib module
Workaround: yum install zlib zlib-devel
then recompile install python
recommend our python learning sites to see how seniors are learning! From basic python script, reptiles, django, data mining, programming techniques, as well as to combat zero-based sorting data items, given to every love learning python small partner! Python veteran day have to explain the timing of technology, to share some of the ways to learn and need to pay attention to small details, click on Join us python learner gathering

发布了52 篇原创文章 · 获赞 122 · 访问量 8万+

Guess you like

Origin blog.csdn.net/haoxun03/article/details/104348852