# Python Tarfile Module

The `tarfile` module makes it possible to read and write tar archives, including those using gzip, bz2 and lzma compression.

## Importing the Module

```python
import tarfile
```

## Reading Tar Files

To open a tar file for reading, use `tarfile.open()`.

```python
import tarfile

with tarfile.open('example.tar', 'r') as tar:
    # List all files in archive
    for member in tar.getmembers():
        print(member.name)
        
    # Extract all files
    tar.extractall(path="extracted_files")
```

## Writing Tar Files

To create a new tar file, open it in write mode (`'w'`).

```python
import tarfile

with tarfile.open('sample.tar', 'w') as tar:
    tar.add('file.txt')
    tar.add('directory_name')
```

## Compression

You can create compressed archives by specifying the compression mode in `open()`.

*   `'w:gz'`: Open for gzip compressed writing.
*   `'w:bz2'`: Open for bzip2 compressed writing.
*   `'w:xz'`: Open for lzma compressed writing.

```python
import tarfile

with tarfile.open('sample.tar.gz', 'w:gz') as tar:
    tar.add('file.txt')
```

## Appending to Tar Files

To append to an existing tar file, use mode `'a'`. Note that appending is not possible for compressed archives.

```python
import tarfile

with tarfile.open('sample.tar', 'a') as tar:
    tar.add('another_file.txt')
```

[[programming/python/python]]