The following is an example of decompressing zip files and deleting files under Python. It has a good reference value and I hope it will be helpful to everyone. Let's take a look together
Use python to download data. The downloaded data is in zip format. Because there are thousands of such files, we directly add the content of the decompressed zip file to the crawler program, and because The amount of data is large, so in order to save space, the zip file is deleted immediately after decompression.
Let’s first introduce the decompression method:
import zipfile filename = '/home/username/work/1.zip' fz = zipfile.ZipFile(filename, 'r') for file in fz.namelist(): fz.extract(file, path)
The following is to delete the file:
If the file exists, delete it.
import os if os.path.exists(filename): os.remove(filename)
Here’s how to delete a folder:
import os #删除空文件夹,若文件夹非空,会报错 path = '/home/username/work/one/' os.rmdir(path) #删除非空文件夹或空文件夹,更强大 import shutil shutil.rmtree(path) #判断文件夹是否存在,方法和判断文件存在与否是一样的 if os.path.exists(path): os.rmdir(path)
and above, welcome to communicate!
##
The above is the detailed content of Examples of decompressing zip files and deleting files under python_python. For more information, please follow other related articles on the PHP Chinese website!