Example of using Python to read and write and compress and decompress files _python

Source: Internet
Author: User
Tags readline

Read and write files
First Look at an example:

f = open (' Thefile.txt ', ' W ')  #以写方式打开,
try:
  f.write (' Wokao ')
finally:
  f.close ()

How files are opened:

f = open (' file ', ' mode ')
' R ': Read-only (default). If the file does not exist, an error is thrown)
' W ': Write-only (files are created automatically if the file is not present), the F.read () method cannot be called, and when F.write () is invoked, the original contents of the file are emptied
' a ': Append to the end of file
' r + ': Read and Write

If you need to open the file in binary mode, you need to precede mode with the character "B", such as "RB", "WB", etc.

Properties of File:

F.closed #标记文件是否已经关闭, overwritten by close ()
f.encoding #文件编码
f.mode #打开模式
f.name #文件名
f.newlines # The line-wrapping mode used in the file is a tuple
f.softspace #boolean型, typically 0, which is said to be used for print

How to read and write files:

F.read ([size]) #size为读取的长度, in bytes
f.readline ([size]) #读一行, if size is defined, it is possible to return only a portion of a row
f.readlines ([size]) #把文件每一行作为一个list的一个成员, and return to this list. In fact, its internal is through the Loop call ReadLine () to achieve. If the size argument is supplied, the size is the total length of the read content, that is, it may read only a portion of the file
f.write (str) #把str写到文件中, and write () does not add a newline character f.writelines after Str
( SEQ) #把seq的内容全部写到文件中. This function is also written faithfully, and does not add anything behind each line
F.close () #关闭文件
f.flush () #把缓冲区的内容写入硬盘
F.fileno () #返回一个长整型的 "file Tag"
The F.isatty () #文件是否是一个终端设备文件 () the F.tell () #返回文件操作标记的当前位置 in the UNIX system
, F.next () #返回下一行 at the beginning of the file
, and the file action tag is shifted to the next line. When you use a file for a statement such as. in file, you call the next () function to implement the traversal of the
F.seek (Offset[,from]) #将文件打操作标记移到offset的位置. This offset is generally calculated relative to the beginning of the file, typically a positive number. However, if the from parameter is provided, the from can be computed from 0 to the beginning and 1 represents the current position as the origin. 2 indicates that the origin is computed at the end of the file. Note that if the file is opened in a A or a + mode, the file action tag is automatically returned to the end of the file each time the write operation is performed.
f.truncate ([size]) #把文件裁成规定的大小, the default is the location where the current file action tag is to be trimmed.

When Python reads a file, it remembers its location in the file, and if the second time you still need to read from scratch, you need to call F.seek (0) to read from the beginning again.

Some examples:

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


compression and decompression files (zip/unzip)
1, a single file compressed 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 ()

Carefully observe the compressed archive.zip, which has a 1.py and a root directory, the root directory has a Install.log
Zip_deflated is a compression flag, if you use it needs to compile the zlib module, if it is only packaged but not compressed, you can change to ZipFile. Zip_stored

2, unzip 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 is a directory in the Archive.zip, there should also be a corresponding directory under the current directory, otherwise it will be an error.

3, compress the entire folder

#!/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 it appears:

Compression requires the (missing) zlib module

Workaround:

Yum Install zlib Zlib-devel

, and then recompile the install Python

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.