Let Python automatically decompress various compressed files in the background!

Liu Zaoqi 2020-11-16 16:19:41
let python automatically decompress various


One 、 Requirements describe

Write a Python Program , Every time you download a compressed file , Automatically decompress the internal files to the current folder and delete the compressed package , What we can learn from this case :

  • os Integrated application of modules
  • glob Integrated application of modules
  • utilize gzip zipfile rarfile tarfile Module decompression file

Two 、 Step analysis and pre knowledge

Code code before the need to interpret complex issues into a number of clear requirements , That is, the logic of the program implementation is :

  1. Check a folder regularly ( Such as download Folder ) Whether the compressed file exists
  2. If there is a new compressed file, unzip it to a new folder in the current folder Delete compressed file
  3. When it comes to compressed files, it is necessary to discuss different compression formats , There are mainly the following 4 Kind of :

When it comes to compressed files, it is necessary to discuss different compression formats , There are mainly the following 4 Kind of :

.gz: namely gzip, Usually only one file can be compressed .tar: It's not a compression tool, it's a packaging tool , Can follow .gz Coordination formation .tar.gz Package compression format of .zip: and .tar.gz It's similar, but you can pack and compress multiple files .rar: Pack and compress files , Originally used for DOS ”

therefore , The judgment logic of whether the file is a compressed file can be as follows :

  1. Create a list of zip suffixes compressed_lst = ['gz', 'tar', 'zip', 'rar']
  2. All file names in the target folder run filename.split(.)[-1] Get suffix
  3. Determine whether the suffix is in compressed_lst in , If it exists, run the subsequent decompression code
  4. If so gz Final document , After decompressing, we need to judge again whether it is with .tar ending , And deal with it accordingly

The decompression code of different compressed files is different , Expand the specific operation in the following code .

3、 ... and 、 Code implementation

The first is acquisition download File names of all files in the folder

import glob
import os
path = r'C:\xxxx\download'
file_lst = glob.glob(path + '/*')
# List derivation
filename_lst = [os.path.basename(i) for i in file_lst]
print(filename_lst)

Next, according to the suffix name of the file to determine whether it needs to be compressed , Let's take a look at the code framework

for i in filename_lst:
if '.' in i:
# Get suffix
suffix = i.split('.')[-1]
# Match the suffixes one by one with the compressed suffixes of each format
if suffix == 'gz':
pass
if ...: # Again, judge whether the new file name is with .tar ending
pass
if suffix == 'tar':
pass
if suffix == 'zip':
pass
if suffix == 'rar':
pass

Here you are 2 A note :

  1. Some files have no suffix , So there may not be ., Use filename.split('.')[-1] Will report a mistake , So we need to judge
  2. With .gz Final document , After decompressing, we need to judge again whether it is with .tar ending , Then we can write the decompression code of the four kinds of compressed files into functions , It can be called separately when it meets the requirements

Handle .gz file

import gzip
def ungz(filename):
filename = filename[:-3] # gz The single file decompression of a file is to remove filename hinder .gz
gz_file = gzip.GzipFile(filename)
with open(filename, "w+") as file:
file.write(gz_file.read())
return filename # This gzip The function needs to return a value to further match untar function

As mentioned repeatedly before gz It's possible that the document is related to tar Document matching , So decompress gz After the file, we need to judge whether it is necessary to untie tar file

Here you can put tar The function of the file is written out ?

Handle .tar file

import tarfile
def untar(filename):
tar = tarfile.open(filename)
names = tar.getnames()
# tar It's a package of files , Unpacking produces a lot of files , So you need to create a folder to store
if not os.path.isdir(filename + "_dir"):
os.mkdir(filename + "_dir")
for name in names:
tar.extract(name, filename + "_dir/")
tar.close()

Handle .zip file

import zipfile
def unzip(filename):
zip_file = zipfile.ZipFile(filename)
# similar tar Unpack , Create a folder to store the extracted files
if not os.path.isdir(filename + "_dir"):
os.mkdir(filename + "_dir")
for names in zip_file.namelist():
zip_file.extract(names, filename + "_dir/")
zip_file.close()

Handle .rar file

import rarfile
def unrar(filename):
rar = rarfile.RarFile(filename)
if not os.path.isdir(filename + "_dir"):
os.mkdir(filename + "_dir")
os.chdir(filename + "_dir")
rar.extractall()
rar.close()

You can see , The four decompression codes are slightly different , I recommend you to experience the difference in the actual demonstration , Decompress and cooperate os.remove() You can delete the compressed package , Now let's look at the logic framework with the decompression function added :

for filename in filename_lst:
if '.' in filename:
suffix = filename.split('.')[-1]
if suffix == 'gz':
new_filename = ungz(filename)
os.remove(filename)
if new_filename.split('.')[-1] == 'tar':
untar(new_filename)
os.remove(new_filename)
if suffix == 'tar':
untar(filename)
os.remove(filename)
if suffix == 'zip':
unzip(filename)
os.remove(filename)
if suffix == 'rar':
unrar(filename)
os.remove(filename)

Real time detection

The simpler way is to set up while True Dead loop coordination time.sleep() sleep , The framework is as follows :

import time
while True:
func()
time.sleep(5) # Sleep seconds can be set a bit larger to avoid over using resources

Finally, change the implementation code of the second step into a function and put it in the loop framework to complete the requirement , The complete code is as follows

import glob
import os
import gzip
import tarfile
import zipfile
import rarfile
import time
path = r'C:\xxxx\download'
file_lst = glob.glob(path + '/*')
filename_lst = [os.path.basename(i) for i in file_lst]
def ungz(filename):
filename = filename[:-3]
gz_file = gzip.GzipFile(filename)
with open(filename, "w+") as file:
file.write(gz_file.read())
return filename
def untar(filename):
tar = tarfile.open(filename)
names = tar.getnames()
if not os.path.isdir(filename + "_dir"):
os.mkdir(filename + "_dir")
for name in names:
tar.extract(name, filename + "_dir/")
tar.close()
def unzip(filename):
zip_file = zipfile.ZipFile(filename)
if not os.path.isdir(filename + "_dir"):
os.mkdir(filename + "_dir")
for names in zip_file.namelist():
zip_file.extract(names, filename + "_dir/")
zip_file.close()
def unrar(filename):
rar = rarfile.RarFile(filename)
if not os.path.isdir(filename + "_dir"):
os.mkdir(filename + "_dir")
os.chdir(filename + "_dir")
rar.extractall()
rar.close()
def unzip_files():
for filename in filename_lst:
if '.' in filename:
suffix = filename.split('.')[-1]
if suffix == 'gz':
new_filename = ungz(filename)
os.remove(filename)
if new_filename.split('.')[-1] == 'tar':
untar(new_filename)
os.remove(new_filename)
if suffix == 'tar':
untar(filename)
os.remove(filename)
if suffix == 'zip':
unzip(filename)
os.remove(filename)
if suffix == 'rar':
unrar(filename)
os.remove(filename)
while True:
unzip_files()
time.sleep(5)

-END-

This article is from WeChat official account. - Get up early Python(zaoqi-python) , author : Chen Xi

The source and reprint of the original text are detailed in the text , If there is any infringement , Please contact the yunjia_community@tencent.com Delete .

Original publication time : 2020-11-07

Participation of this paper Tencent cloud media sharing plan , You are welcome to join us , share .

版权声明
本文为[Liu Zaoqi]所创,转载请带上原文链接,感谢

  1. 利用Python爬虫获取招聘网站职位信息
  2. Using Python crawler to obtain job information of recruitment website
  3. Several highly rated Python libraries arrow, jsonpath, psutil and tenacity are recommended
  4. Python装饰器
  5. Python实现LDAP认证
  6. Python decorator
  7. Implementing LDAP authentication with Python
  8. Vscode configures Python development environment!
  9. In Python, how dare you say you can't log module? ️
  10. 我收藏的有关Python的电子书和资料
  11. python 中 lambda的一些tips
  12. python中字典的一些tips
  13. python 用生成器生成斐波那契数列
  14. python脚本转pyc踩了个坑。。。
  15. My collection of e-books and materials about Python
  16. Some tips of lambda in Python
  17. Some tips of dictionary in Python
  18. Using Python generator to generate Fibonacci sequence
  19. The conversion of Python script to PyC stepped on a pit...
  20. Python游戏开发,pygame模块,Python实现扫雷小游戏
  21. Python game development, pyGame module, python implementation of minesweeping games
  22. Python实用工具,email模块,Python实现邮件远程控制自己电脑
  23. Python utility, email module, python realizes mail remote control of its own computer
  24. 毫无头绪的自学Python,你可能连门槛都摸不到!【最佳学习路线】
  25. Python读取二进制文件代码方法解析
  26. Python字典的实现原理
  27. Without a clue, you may not even touch the threshold【 Best learning route]
  28. Parsing method of Python reading binary file code
  29. Implementation principle of Python dictionary
  30. You must know the function of pandas to parse JSON data - JSON_ normalize()
  31. Python实用案例,私人定制,Python自动化生成爱豆专属2021日历
  32. Python practical case, private customization, python automatic generation of Adu exclusive 2021 calendar
  33. 《Python实例》震惊了,用Python这么简单实现了聊天系统的脏话,广告检测
  34. "Python instance" was shocked and realized the dirty words and advertisement detection of the chat system in Python
  35. Convolutional neural network processing sequence for Python deep learning
  36. Python data structure and algorithm (1) -- enum type enum
  37. 超全大厂算法岗百问百答(推荐系统/机器学习/深度学习/C++/Spark/python)
  38. 【Python进阶】你真的明白NumPy中的ndarray吗?
  39. All questions and answers for algorithm posts of super large factories (recommended system / machine learning / deep learning / C + + / spark / Python)
  40. [advanced Python] do you really understand ndarray in numpy?
  41. 【Python进阶】Python进阶专栏栏主自述:不忘初心,砥砺前行
  42. [advanced Python] Python advanced column main readme: never forget the original intention and forge ahead
  43. python垃圾回收和缓存管理
  44. java调用Python程序
  45. java调用Python程序
  46. Python常用函数有哪些?Python基础入门课程
  47. Python garbage collection and cache management
  48. Java calling Python program
  49. Java calling Python program
  50. What functions are commonly used in Python? Introduction to Python Basics
  51. Python basic knowledge
  52. Anaconda5.2 安装 Python 库(MySQLdb)的方法
  53. Python实现对脑电数据情绪分析
  54. Anaconda 5.2 method of installing Python Library (mysqldb)
  55. Python implements emotion analysis of EEG data
  56. Master some advanced usage of Python in 30 seconds, which makes others envy it
  57. python爬取百度图片并对图片做一系列处理
  58. Python crawls Baidu pictures and does a series of processing on them
  59. python链接mysql数据库
  60. Python link MySQL database