The path to Python (18th) shutil module, ZipFile module, Configparser module

Source: Internet
Author: User

One, Shutil module1,shutil.copyfileobj (FSRC, fdst[, length])

To copy the contents of a file to another file, you need to open the file

  Import Shutil  shutil.copyfileobj (Open ("Old_test.txt", "R"), Open ("New_test.txt", "w"))

  

Output results

2, Shutil.copyfile (SRC,DST)

Copy the file contents to another file, do not need to open the file, in fact, CopyFile called the Copyfileobj

  
  Import Shutil  shutil.copyfile ("Old_test.txt", "New.txt")

  

Output results

3, Shutil.copymode (SRC,DST)

Copy permissions only, do not change file contents, groups, and users.

  
  Import Shutil  shutil.copymode ("Old_test.txt", "New.txt")

  

Output results

4.shutil.copystat (SRC, DST)

Copy permissions only. Content, group, user are not changed

  
  Import Shutil  shutil.copystat ("Old_test.txt", "New.txt")

  

Output results

5.shutil.copy (SRC, DST)

Copying files and Permissions

  
  Import Shutil  shutil.copy ("Old_test.txt", "New.txt")

  

Output results

6.shutil.copy2 (SRC, DST)

Copying files and status information

  
  Import Shutil  shutil.copy2 ("Old_test.txt", "New.txt")

  

Output results

7,shutil.copytree (SRC, DST, Symlinks=false, Ignore=none)

Shutil.copytree

Recursive go-to-copy folder, write permission to the directory to be written

Example

  
  Shutil.copytree (' Folder1 ', ' Folder2 ', ignore=shutil.ignore_patterns (' __init__.py ', ' tmp* '))  #shutil. ignore_ Patterns (*patterns) #ignore代表排除

  

Output results

8,shutil.rmtree (path[, ignore_errors[, onerror])

To delete a file recursively

  
  Shutil.rmtree (' Folder1 ')

  

9.shutil.move (SRC, DST)

To move a file recursively, it is like the MV command, which is actually renamed. DST can be a file name or a directory, and the destination file exists to overwrite.

  
  Shutil.move (' Folder1 ', ' Folder3 ')

  

Example

  
  Import Shutil  shutil.move ("a", "temp")

  

Output results

10.shutil.make_archive (base_name, Format,...)

Create a compressed package and return the file path, for example: Zip, tar

Create a compressed package and return the file path, for example: Zip, tar

    • Base_name: The file name of the compressed package, or the path to the compressed package. Only the file name is saved to the current directory, otherwise saved to the specified path,

    • Format: Compressed package type, "Zip", "tar", "Bztar", "Gztar"

    • Root_dir: Folder path to compress (default current directory), which directory or file to package (that is, the source file)

    • Owner: User, default Current user

    • Group: Groups, default current group

    • Logger: Used to log logs, usually logging. Logger Object

Example

  Import Shutil  shutil.make_archive ("Test_package_bak", "Zip", "test_package")  #对文件夹下的test_package文件夹进行打包

  

Output results

11, shutil.unpack_archive ()

Decompression, you can specify the decompression directory, or the default decompression to the current working directory .

Shutil.unpack_archive (FILENAME=HH, Extract_dir=local_dir)

  

Example

  Import Shutil  shutil.unpack_archive ("Test_package_bak.zip", Extract_dir=r "D:\t1")

  

Output results

Second, ZipFile module compression & Decompression

Shutil Processing of compressed packets is done by calling the ZipFile and tarfile two modules in detail:zipfile Compression & Decompression, Tarfile compression & decompression

Simple Compression Example
ZipFile. ZipFile (filename[, mode[, compression[, AllowZip64]])

  

Parameter description

    • FileName: The compressed file name,
    • mode and normal file operation, ' R ' means to open an existing read-only zip file, ' W ' means to empty and open a write-only zip file, or to create a write-only zip file; ' A ' means to open a zip file and add content.
    • Compression represents a compressed format with an optional compression format of only 2: Zip_store; Zip_deflated. Zip_store is default, means no compression, zip_deflated means compression (that is, compression rate)
    • When ALLOWZIP64 is true, 64-bit compression is supported, in general, this option is used when the compressed file is larger than 2G, which is false by default because UNIX systems do not support it.

F.write (f (Filename[,arcname[,compression_type])

  

Writes a file to a zip file, compressing the file

The file filename outside the zip is written to a sub-file named Arcname (of course arcname is also a path with a relative zip package), Compression_type specifies the compression format, also zip_stored or zip_deflated. F must be opened in a way that is w or a to successfully write to the file.

Compression examples

  Import ZipFile  ?  f = zipfile. ZipFile ("Test.zip", mode= "W", Compression=zipfile. zip_deflated)  f.write ("Old_test.txt")   #也可以写文件完整路径名  f.write ("test.py")  f.close ()  print ( F.namelist ())  #查看压缩包文件列表, F is an object instantiated ZipFile, where the NameList () method is called

  

Output results

  
  [' Old_test.txt ', ' test.py ']

  

There are two ways to compare similar, pay attention to distinguish.

    • f.writeRefers to copying an already existing file to a compressed package, including all files in the path Jia he the file under it.

    • f.writestris to create a new folder and file directly in the package, and the data parameter is the content to write to the file.

Decompression Examples

F.extract (Member[,path[,pwd]) extract a file from the zip, put it under the specified path, PWD is the password for the encrypted zip file, member is the file name to extract

F.extractall (Path[,pwd]) extracts all files from the current zip in the same directory structure as shown in NameList and puts them under path.

Path extract directory, password This option is required when a zip file has a password

Example

  Import ZipFile  f = zipfile. ZipFile ("Test_package.zip", mode= "R") #注意此时解压不要用 "W" format, the "W" format will empty the compressed package file  F.extractall (path=r "d:\testaaa")  #将压缩包解压到d: \testaaa  f.extract ("Old_test.txt")  #提取压缩包中的一个文件到当前目录  f.close ()

  

Output results

Advanced Applications

Zipfile.is_zipfile (filename) to determine if a file is a compressed file

Zipfile.namelist () Returns a list of files

Example

  Import ZipFile  f = zipfile. ZipFile ("Test_package.zip", mode= "R") #注意此时解压不要用 "W" format, the "W" format will empty the compressed package file  print (F.namelist ())  print ( Zipfile.is_zipfile ("Test_package.zip"))

  


?

Note At this time, do not use the "W" format, the "W" format will empty the compressed package file

Output results

  [' encode_decode problem. Py ', ' new_test.txt ', ' old_test.txt ', ' test.py ', ' test.xml ', ' test1.py ', ' test2.py ', ' test3.py ', ' test6.py ', ' testxml.xml ', ' Client 1.py ', ' server. Py ']  True  ?

  

three, Configparser module

The Configparse module is used to generate and modify, parse (read analysis, get data) Common configuration documents, most of such configuration file name format is Xxx.ini, for example, MySQL configuration files.

The name of the current module is changed to Configparser in the Python 3.x version. (Python2 initial capital letter)

configuration File Sample Description
    ##### INI File example ########     [Section1]        name = Nicholas Age  = All      [Section2]  name:python Age  =     # # # # File Format Description #########  [XXX]  stands for node  xx = XX or xx:xx represents parameters  

  

Example

Configuration file Contents

File name "Test.ini"

File contents

    [DEFAULT]  Default_mykey=myvalue  ?  [Section_a]  KEYA1=VALUEA1  keya2=valuea2  keya3=valuea3  ?  [Section_b]  Keyb1=valueb1  keyb2=valueb2  keyb3=valueb3  ?  [Db]  db_host=127.0.0.1  db_port=5432  db_user=admin  db_pass=letmein  db_name=test  db_url = JDBC :p ostgresql://% (db_host) s:% (db_port) s/% (db_name) s

  

Python file operations

  
  Import Configparser? Con = configparser.  Configparser () #实例化创建一个对象 con.read ("Test.ini") #调用对象的read方法读取配置文件?  Print (Con.sections ()) #获取所有节点名称, default # output results [' section_a ', ' section_b ', ' Db '] are not shown Print (con.options (' section_a ')) #获取指定节点的所有key # output [' Keya1 ', ' keya2 ', ' keya3 ', ' Default_mykey '] # Note that when the key value pair data is processed, the key name is all  Convert to lowercase, and automatically add the default node key value? Print (Con.items (' section_a ')) #获取指定节点的键值对 #输出结果 [(' Default_mykey ', ' myvalue '), (' Keya1 ', ' valuea1 '), (' Keya2 ', '  Valuea2 '), (' Keya3 ', ' Valuea3 ')] # Here the output is also automatically added to the default key value pair?  Print (Con.get (' section_a ', "keya1")) #获取指定节点的指定key的value # output VALUEA1?  Print (Con.getint ("Db", "Db_port")) #获取节点section1的age属性, the attribute needs to be int, otherwise valueerror # output 5432?  Print (Con.has_section ("section")) #检查指定节点是否存在, returns TRUE or False # output false?  Print (Con.has_option ("Section_a", "keya1")) #检查指定节点中是否存在某个key, returns TRUE or False # output true?  ?  # Loop find key for I in con["Section_a"]: print (i)? # value in dictionary format data = con["Section_a" ["Keya1"] Print (data) # output Valuea1? # The Judgment node is not in the object print ("Section_a" in con) # output True

  

other additions and deletions to check grammar
  Import Configparser  ?  Con = configparser. Configparser ()  #实例化创建一个对象  con.read ("Test.ini")  #调用对象的read方法读取配置文件  ?  Con.add_section ("New_section") #添加一个节点, the node name is New_section, at which point the added node has not been written to the file,                                 # need to write method written to the file  ?  Con.remove_section ("Section_b")  #删除一个节点, the node name is Section_b, deleted the memory node,                                   # But the file is not deleted, the Write method needs to be deleted, there are remove_ Option                                     ?  Con.set ("Section_a", "K1", "v1") # Adds a key-value pair to the existing node K1 = v1,                                   # If the node does not exist then an error, if the key already exists, then modify value, here also need to                                   #有 Write method to manipulate the file  ?  Con.write (Open ("Test.ini", "W"))  #将修改写入文件

  

Output results

Supplemental remove_option (section, option)

Removes the specified option from the specified node. If this part does not exist, please raise nosectionerror. Returns true if the existing option is deleted, otherwise false.

The path to Python (18th) shutil module, ZipFile module, Configparser module

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.