Example of reading and writing and compressing and decompressing files using python

Source: Internet
Author: User
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, throws an error) ' W ': Write-only (if the file does not exist, the file is created automatically), the F.read () method cannot be called at this time, and when F.write () is called, the original contents of the file ' a ': appended to the end of the file ' r+ ': Read-write

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

Properties of the file:

F.closed #标记文件是否已经关闭, overwriting f.encoding #文件编码f by close () mode #打开模式f. Name #文件名f. newlines #文件中用到的换行模式, is a tuplef.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 part of a row f.readlines ([size]) # Take each line of the file as a member of a list and return to the list. In fact, its internal is through the Loop call ReadLine () to achieve. If you provide a size parameter, size is the total length of the read content, that is, it may be read only to a portion of the file F.write (str) #把str写到文件中, and write () does not add a newline character after Str f.writelines (seq) # Write the contents of the SEQ to the file. This function simply writes faithfully and does not add anything behind each line F.close () #关闭文件f. Flush () #把缓冲区的内容写入硬盘f. Fileno () #返回一个长整型的 "file label" F.isatty () # Whether the file is a terminal device file (Unix system) F.tell () #返回文件操作标记的当前位置, with the beginning of the file as the Origin F.next () #返回下一行, and the file action tag is shifted to the next line. When a file is used for a statement such as for ... in file, it is called 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 and is generally a positive number. However, if the from parameter is not necessary, from can be 0 for the beginning of the calculation, 1 for the current position as the origin. 2 means that the end of the file is calculated as the origin. Note that if the file is opened in a or a + mode, the file action tag is automatically returned to the end of the file each time the write operation is made. F.truncate ([size]) #把文件裁成规定的大小, the default is the location that is cropped to the current file action tag.

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

Some examples:

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

Compress and Decompress files (zip/unzip)
1, a single file compressed into a ZIP file

#!/usr/bin/pythonimport Zipfilef = ZipFile. ZipFile (' Archive.zip ', ' W ', ZipFile. zip_deflated) f.write (' 1.py ') f.write ('/root/install.log ') f.close ()

After careful observation of the compressed archive.zip, there is a 1.py and a root directory, the root directory has a Install.log
Zip_deflated is a compression flag, if used it needs to compile the zlib module, if it is only packaged and not compressed, you can change to ZipFile. Zip_stored

2. Unzip the zip file

#!/usr/bin/pythonimport zipfilezfile = 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 be a corresponding directory in the current directory, otherwise it will be an error.

3. Compress the entire folder

#!/usr/bin/pythonimport zipfileimport OSF = 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 and install Python

These are the contents of the example of using Python to read and write and compress and decompress files, and please pay attention to topic.alibabacloud.com (www.php.cn) for more information!

  • 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.