博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python tarfile模块
阅读量:2531 次
发布时间:2019-05-11

本文共 4607 字,大约阅读时间需要 15 分钟。

Python tarfile module is used to read and write tar archives. Python provides us excellent tools and to manage compressed files, which includes (but not limited to) performing file and directory compression with different mechanisms like gzip, bz2 and lzma compression.

Python tarfile模块用于读取和写入tar归档文件。 Python为我们提供了出色的工具和来管理压缩文件,其中包括(但不限于)使用gzip,bz2和lzma压缩等不同机制执行文件和目录压缩。

In this post, we will see various practical demonstrations of Python tarfile module functions. This is similar to function. Let’s get started.

在本文中,我们将看到Python tarfile模块功能的各种实际演示。 这类似于函数。 让我们开始吧。

Python tarfile模块 (Python tarfile module)

Python tarfile module provides us functions to perform various operations like:

Python tarfile模块为我们提供了执行各种操作的功能,例如:

  • read and write gzip, bz2 and lzma archives

    读写gzip,bz2和lzma档案
  • read and write POSIX.1-1988 (ustar) format

    读写POSIX.1-1988(ustar)格式
  • read and write support for GNU tar format

    对GNU tar格式的读写支持
  • read and write gzip, bz2 and lzma archives

    读写gzip,bz2和lzma档案

Apart from these features, we can also handle directories and restore file information like timestamp, access permissions and owner.

除了这些功能之外,我们还可以处理目录并还原文件信息,例如时间戳,访问权限和所有者。

检查TAR文件的有效性 (Checking validity of TAR files)

We will start by a simplest example of checking if a file is a valid TAR file. We will use is_tarfile() function to do this:

我们将从检查文件是否为有效TAR文件的最简单示例开始。 我们将使用is_tarfile()函数执行此操作:

import tarfilefor file_name in [ 'README.txt', 'example.tar.gz' ]:    try:        print(file_name, tarfile.is_tarfile(filename))    except (IOError, err):        print(file_name, err)

Let’s run this example and check the output:

python tarfile check validity
Note that these files should exist in the directory you run this script in.

让我们运行此示例并检查输出:

请注意,这些文件应该存在于运行此脚本的目录中。

读取TAR文件元数据 (Reading TAR file metadata)

In this section, we will study metadata related to a TAR file like what files does it contain, using the open() and getnames() function:

在本节中,我们将使用open()getnames()函数研究与TAR文件相关的元数据,例如它包含的文件:

import tarfilet = tarfile.open('example.tar.gz', 'r')print("Files in TAR file:")print(t.getnames())

Let’s run this example and check the output:

python tarfile example, python tarfile
Note that, we just put sample files in this TAR to demonstrate.

让我们运行此示例并检查输出:

注意,我们只是将样本文件放在此TAR中进行演示。

Let’s get a little deep in getting the file’s metadata before moving on to next example. We will print its size and much more information related to it:

在继续下一个示例之前,让我们深入了解文件的元数据。 我们将打印它的大小以及与其相关的更多信息:

import tarfileimport timet = tarfile.open('example.tar.gz', 'r')for info in t.getmembers():    print(info.name)    print('Modified:', time.ctime(info.mtime))    print('Mode    :', oct(info.mode))    print('Type    :', info.type)    print('Size    :', info.size, 'bytes')

When we run this program, we can see much more information related to the files:

python tar file metadata

当我们运行该程序时,我们可以看到更多与文件有关的信息:

从档案中提取文件 (Extracting Files From an Archive)

Here, we will extract files from the archive file:

在这里,我们将从存档文件中提取文件:

import tarfilet = tarfile.open('example.tar.gz', 'r')for file_name in [ 'TarFolder/README.txt', 'TarFolder/tarfile_validity.py' ]:    try:        f = t.extractfile(file_name)    except KeyError:        print('ERROR: Did not find %s in tar archive' % file_name)    else:        print(file_name, ':', f.readlines())

Let’s run this example and check the output:

python tarfile extractfile

让我们运行此示例并检查输出:

将文件添加到存档 (Adding Files to an Archive)

Here, we will add files to an archive file:

在这里,我们将文件添加到存档文件中:

import tarfileprint('creating archive')out = tarfile.open('example.tar.gz', mode='w')try:    print('adding README.txt')    out.add('README.txt')finally:    print('closing tar archive')    out.close()print('Contents of archived file:')t = tarfile.open('example.tar.gz', 'r')for member in t.getmembers():    print(member.name)

Let’s run this example and check the output:

python tarfile add file
Here, it is worth noticing that ‘w’ doesnn’t preserve previous contents of the file. We can instead use ‘a’ mode to append files to an archive.

让我们运行此示例并检查输出:

在这里,值得注意的是'w'不会保留文件的先前内容。 相反,我们可以使用“ a”模式将文件追加到存档中。

将文件追加到存档 (Appending Files to an Archive)

Here, we will append files to an archive file, instead of using the ‘w’ mode:

在这里,我们将文件追加到存档文件中,而不是使用“ w”模式:

import tarfileprint('creating archive')out = tarfile.open('example.tar.gz', mode='a')try:    print('adding README.txt')    out.add('README.txt')finally:    print('closing tar archive')    out.close()print('Contents of archived file:')t = tarfile.open('example.tar.gz', 'r')for member in t.getmembers():    print(member.name)

Let’s run this example and check the output:

python tarfile append
Clearly, after adding README.txt to the TAR, there now exists 2 files.

让我们运行此示例并检查输出:

显然,在将README.txt添加到TAR之后,现在存在2个文件。

Reference: .

参考: 。

翻译自:

转载地址:http://nymzd.baihongyu.com/

你可能感兴趣的文章
程序员最想得到的十大证件,你最想得到哪个?
查看>>
我的第一篇CBBLOGS博客
查看>>
【MyBean调试笔记】接口的使用和清理
查看>>
07 js自定义函数
查看>>
jQueru中数据交换格式XML和JSON对比
查看>>
form表单序列化后的数据转json对象
查看>>
[PYTHON]一个简单的单元測试框架
查看>>
iOS开发网络篇—XML数据的解析
查看>>
[BZOJ4303]数列
查看>>
一般处理程序在VS2012中打开问题
查看>>
C语言中的++和--
查看>>
thinkphp3.2.3入口文件详解
查看>>
POJ 1141 Brackets Sequence
查看>>
Ubuntu 18.04 root 使用ssh密钥远程登陆
查看>>
Servlet和JSP的异同。
查看>>
虚拟机centOs Linux与Windows之间的文件传输
查看>>
ethereum(以太坊)(二)--合约中属性和行为的访问权限
查看>>
IOS内存管理
查看>>
middle
查看>>
[Bzoj1009][HNOI2008]GT考试(动态规划)
查看>>