An example of using Python to read, write, and decompress files,

Source: Internet
Author: User

An example of using Python to read, write, and decompress files,

Read/write files
First, let's look at an example:

F = open('thefile.txt ', 'w') # Open in write mode. try: f. write ('wokao') finally: f. close ()

File opening method:

F = open ('file', 'Mode') 'r': Read-Only (default. If the file does not exist, an error is thrown.) 'W': Write-only (if the file does not exist, the file is automatically created). At this time, f. read () method, and when calling f. during write (), the original content 'A' is cleared and appended to the end of the file 'r + ': read/write

To open a file in binary mode, add the character "B" after the mode, such as "rb" and "wb ".

File attributes:

F. closed # MARK whether the file has been closed, and rewrite f by close. encoding # file encoding f. mode # open mode f. name # file name f. newlines # The line feed mode used in the file is a tuplef. softspace # boolean type, generally 0, is said to be used for print

File read/write method:

F. read ([size]) # size is the read length, in bytes. readline ([size]) # Read a row. If the size is defined, it is possible that only part of the row is returned. readlines ([size]) # Use each row of the file as a member of a list and return this list. In fact, it is implemented by calling readline () cyclically. If the size parameter is provided, size indicates the total length of the read content, that is, it may be read-only to a part of the file f. write (str) # write str to the file. write () does not add a line break f. writelines (seq) # Write All seq content to a file. This function is only faithfully written and will not add anything behind each line. close () # close the file f. flush () # Write the buffer content to the hard disk f. fileno () # returns a long integer "file tag" f. isatty () # Whether the file is a terminal device file (in unix) f. tell () # Return the current position marked by the file operation, starting with the file as the origin f. next () # return the next row, and move the operation mark of the file to the next row. Use a file... In file is to call the next () function to traverse f. seek (offset [, from]) # Move the operation mark of the file to the offset position. This offset is generally calculated relative to the beginning of the file, and is generally a positive number. However, if the from parameter is provided, the from parameter can be set to 0, indicating that the from is calculated from the beginning, and 1 indicates that the current position is used as the origin. 2 indicates that the origin is the end of the file. Note that if the file is opened in a or a + mode, the Operation mark of the file is automatically returned to the end of the file each time the file is written. F. truncate ([size]) # crop the file to the specified size. The default value is the location marked by the current file operation.

When reading a file, Python remembers its position in the file. If you still need to read the file from the beginning for the second time, you need to call f. seek (0) to read the file from the beginning again.

Some examples:

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


Zip/unzip)
1. Compress a single file 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()

The archive.zip file contains a 1. py directory and a root directory. The root directory contains an install. log file.
ZIP_DEFLATED is the compression flag. If you want to use it to compile the zlib module, you can change it to zipfile. ZIP_STORED if it is only packaged but not compressed.

2. decompress 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 archive.zip, the corresponding directory should also exist in the current directory; otherwise, an error will be reported.

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:

Compression requires the (missing) zlib module

Solution:

yum install zlib zlib-devel

And then re-compile and install python

Related Article

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.