Python tarfile module

python tarfile module


 Get along well with Python

This is my participation 8 The fourth of the yuegengwen challenge 8 God , Check out the activity details : 8 Yuegengwen challenge

Review review

The modules supporting archive compression and decompression are as follows :

  • Python File directory advanced operation -shutil modular , In addition to the documentation / Copy directory 、 Move 、 Delete operation , It also supports archiving of files 、 Compression and decompression methods .

  • zipfile modular , Provide ZipFile Classes and corresponding methods , establish ZiP file

In this issue , We will continue to learn how to compress and decompress files and directories -tarfile Learning and using module related methods

I don't say much nonsense , Put on the headphones 、 Play music , Start today's learning journey ~

1. tarfile Module common methods

tarfile The module also supports compression and decompression , When compressing , If you compress a folder , The content will also be compressed

meanwhile tarfile It also provides reading and writing functions , The common methods are as follows :

Method effect
tarfile.TarFile An operation is provided tar Archive interface
tarfile.TarInfo One TarInfo The object represents TarFile A member of
tarfile.open(filename,mode) Create and return one TarFile object
tarfile.is_tarfile(name) Determine if the document is Tarfile, Yes, go back to True
tarfile.ENCODING Default character encoding ,Windows Up for "utf-8"
tarfile.USTAR_FORMAT POSIX.1-1922(ustar) Format
tarfile.GUN_FORMAT GUN tar Format
tarfile.PAX_FORMAT POSIX.1-2001(pax) Format

Important note :

  • tarfile.open(filename,mode): Create open Tarfile object

    (1) establish Tarfile object filename Postposition and mode Value correspondence

    (2)mode The default is "r", read only mode

    (3) File format and mode The comparison table is as follows :

     Format and mode Comparison table

  • tarfile.TarFile: An operation is provided tar Archive interface

    (1)TarFile Instance objects can be used with the above Manager

    (2)Tarfile When an exception occurs to an object, the compressed file opened for writing will not be terminated . It will only shut down

    (3)Tarfile Class provides methods to manipulate compressed files, such as add(),close(),getnames() Other methods

    Method effect
    add(name) Add the file to the compressed file
    addfile(tarinfo) take tarinfo Add to compressed file
    getmeber(name) Get the name of the compressed file name The object of
    getmebers() Get all the file objects in the compressed file
    getnames() Get the file name list in the compressed file
    list() Print the contents of the compressed file to the system
    next() Returns the next file object of the compressed document
    extract(nanem,path) Unzip a single file
    extractall(path) Unzip all files
    close() Close compressed file
  • tarfile.TarInfo: One TarInfo The object represents TarFile A member of

    (1)TarInfo Object passing Tarfile Of getmember()、getmembers() and gettarinfo() Method to get

    (2)TarInfo Save all properties of the file ( Such as : file type 、 file size 、 Modification time 、 jurisdiction ), It also provides a method to judge its file type .

    Method / Property name effect
    name Compressed file member name
    linkname Compressed file member name
    gname Group name
    size file size
    mode File permissions
    isfile() Judge TarInfo Whether the object is an ordinary file
    isdir() Judge TarInfo Whether the object is a directory
    ischr() Judge TarInfo Whether the object is a byte device
    isfifo() Judge TarInfo Whether the object is a FIFO The Conduit

2. tarfile Module compression and decompression operation

Compressed file directory structure

 test.tar,gz
│ test1.txt
│
├─New
│ New10_test.txt
│
├─old
│ old6_test
│ test.txt
 Copy code 

Compression implementation steps :

  1. Create a compressed file :tp = tarfile.open(file_path, mode)

  2. Add content :tp.add(file_name, arcname)

  3. Close file :tp.close()

import tarfile
tf = tarfile.open("test.tar.gz","w:gz")
tf.add('test1.txt')
tf.add('./New/New10_test.txt')
tf.add('./old/old6_test/test.txt')
tf.list()
tf.close()
 Copy code 

 Compressed file running results

3. tarfile Module decompression operation

decompression :

  1. establish tarfile example , open tar file :tp = tarfile.open(file_path, 'r')

  2. Decompress the file :

    (1) Extract the specified single file :tp.extract(file_name, path)
    (2) decompression tar All files in :tp.extractall(path)

  3. Close file :tp.close()

tf = tarfile.open("test.tar.gz","r:gz")
tf.extract("test1.txt","./tar2")
tf.extractall("./tar2")
tf.close()
 Copy code 

summary

In this issue , We are right. Python Provides the ability to compress and decompress files tarfile Module related methods, such as open(),add() etc.

meanwhile , in the light of tarfile The classes and methods provided by the module , Learn and master , Help improve efficiency in our daily work

The above is the content of this issue , Welcome all the big guys to praise and comment , See you next time ~

版权声明
本文为[Little cute in the circle of friends]所创,转载请带上原文链接,感谢
https://pythonmana.com/2021/08/20210808140809077p.html

  1. 小白量化投资交易入门课(python入门金融分析)
  2. Python:PyCharm选择性忽略PEP8警告
  3. Python: pychar selectively ignores pep8 warnings
  4. Django-模板
  5. Django template
  6. Python正则表达式大全
  7. 最全Python正则表达式来袭
  8. A python knowledge for Xiaobai
  9. 2. Flexible pandas index
  10. 1. Get to know pandas
  11. See how I use Python to create a magic with baby (one play can play for a day)?
  12. Wow, python can do real-time translation
  13. Python经典编程习题100例
  14. 100 examples of Python classic programming exercises
  15. Invincible, with Python for English teachers to develop a magic tool for English composition correction (support primary school to IELTS)
  16. 抖音数据采集教程,最全python库selenium自动化使用
  17. Pandas 11-综合练习
  18. Pandas 11 - comprehensive exercises
  19. Pandas基础|用户游览日志时间合并排序
  20. python自学 第三章 python语言基础之保留字、标识符与内置函数
  21. python学习例程3-函数
  22. Python GUI 之Tkinter小结 - 知乎
  23. Pandas foundation | user travel log time merge sort
  24. Chapter 3 reserved words, identifiers and built-in functions of the foundation of Python
  25. Tkinter summary of Python GUI - Zhihu
  26. 【Python常用包】itertools
  27. Itertools
  28. [Python] Matplotlib 图表的绘制和美化技巧
  29. Drawing and beautifying skills of [Python] Matplotlib chart
  30. Drawing and beautifying skills of [Python] Matplotlib chart
  31. Python序列之列表(一)
  32. Python解析库lxml与xpath用法总结
  33. Python解析库lxml与xpath用法总结
  34. Usage Summary of Python parsing library lxml and XPath
  35. Usage Summary of Python parsing library lxml and XPath
  36. Python web/HTML GUI
  37. Why is sanic better than Django flame?
  38. Wechat applet Python sends subscription message
  39. Invincible, with Python for English teachers to develop an English composition correction artifact (support primary school to IELTS)
  40. How can I use Python to create a magic with children (one can play for one day)?
  41. Pandas module
  42. Machine learning in Python - Boston house price forecast
  43. 50 Great Python modules
  44. Share the survival status of Python practitioners and tell you the real salary of general programmers
  45. Pandas basic operation update
  46. Python Programming day02 Python operator
  47. Usage Summary of Python parsing library lxml and XPath
  48. 1. First meeting pandas
  49. Conversion between Python and base conversion between Python and base
  50. Basics of Python
  51. Fundamentals of python (XIV): errors and exceptions
  52. Fundamentals of python (8): time related modules
  53. Fundamentals of python (I): necessary knowledge for getting started
  54. Operators in Python 3
  55. The list of national computer non graduate schools (captured by Python), just look at this one!
  56. Python data visualization: Seaborn
  57. Quick start pandas (lower)
  58. Operators in Python 3
  59. Python basic syntax