Python Short Demo: Unpack VIIRS .tar Files from CLASS and Extract .nc Files

VIIRS granules files ordered from NOAA's CLASS archive come bundled as .tar files. This Python function can be used to "unpack" .tar files and extract the individual granules files in .nc format.

Please acknowledge the NOAA/NESDIS/STAR Aerosols and Atmospheric Composition Science Team if using any of this code in your work/research!

# Library for working with tar files
import tarfile

# Unpack .tar files
# "file_list" is the list of .tar files to be unpacked
# "save_path" is the directory where unpacked .nc files will be saved

def unpack_tar(file_list, save_path):
    for tar_file_name in file_list:
        tar = tarfile.open(tar_file_name)
        tar.extractall(path=save_path)
        tar.close()

Demonstration of how to use the function: The user enters the "file_path" (directory where .tar files are located) and "save_path" (directory where unpacked .nc files will be saved) parameter variables. In this example, both directories are assumed to be the current working directory (cwd), set using the pathlib module.

# Import Python packages

# Module to set filesystem paths appropriate for user's operating system
from pathlib import Path

# Library for working with tar files
import tarfile


# Unpack .tar files
def unpack_tar(file_list, save_path):
    for tar_file_name in file_list:
        tar = tarfile.open(tar_file_name)
        tar.extractall(path=save_path)
        tar.close()

# Main function
if __name__ == "__main__":

    # Enter directory where .tar files are located
    file_path = Path.cwd()  # Current working directory

    # Enter directory where unpacked .nc files will be saved
    save_path = Path.cwd()  # Current working directory
	
    # Collect all .tar files in the specified directory
    file_list = file_path.glob('*.tar')
    
    # Call function to unpack .tar files
    unpack_tar(file_list, save_path)
    print('Done!')