使用GzipFile()函数在Python中压缩和解压XML文件
发布时间:2023-12-27 23:27:08
在Python中,可以使用gzip模块中的GzipFile()函数来对XML文件进行压缩和解压。GzipFile()函数提供了压缩和解压缩文件的方法。下面是使用GzipFile()函数进行压缩和解压缩的示例。
示例1: 压缩XML文件
import gzip
def compress_file(input_file, output_file):
with open(input_file, 'rb') as f_in:
with gzip.open(output_file, 'wb') as f_out:
f_out.writelines(f_in)
input_file = 'example.xml'
output_file = 'example.xml.gz'
compress_file(input_file, output_file)
在上面的示例中,首先使用open()函数打开要压缩的XML文件,并以二进制模式读取文件内容。然后使用gzip.open()函数创建一个压缩文件,并以二进制模式写入压缩内容。通过传递writelines()函数来实现将原始XML文件内容写入压缩文件。最后,通过关闭文件句柄以及with语句中的上下文管理器来确保资源释放。
示例2: 解压缩XML文件
import gzip
def decompress_file(input_file, output_file):
with gzip.open(input_file, 'rb') as f_in:
with open(output_file, 'wb') as f_out:
f_out.writelines(f_in)
input_file = 'example.xml.gz'
output_file = 'example.xml'
decompress_file(input_file, output_file)
在上面的示例中,首先使用gzip.open()函数打开已压缩的文件,并以二进制模式读取。然后使用open()函数创建一个解压缩文件,并以二进制模式写入解压缩内容。通过传递writelines()函数来实现将原始压缩文件内容写入解压缩文件。最后,通过关闭文件句柄以及with语句中的上下文管理器来确保资源释放。
可以根据实际情况对上述示例进行修改以适应不同的XML文件压缩和解压缩需求。
