import os
import tarfile
def archive_files(file_list, archive_name):
"""
Archives the content of a list of files into a tar archive.
Args:
file_list (list): A list of file paths to archive.
archive_name (str): The name of the tar archive to create.
"""
try:
with tarfile.open(archive_name, "w") as tar:
for file_path in file_list:
if os.path.exists(file_path):
tar.add(file_path, arcname=os.path.basename(file_path)) # Add file to archive, preserving name
else:
print(f"Warning: File not found: {file_path}")
print(f"Successfully created archive: {archive_name}")
except Exception as e:
print(f"Error creating archive: {e}")
if __name__ == '__main__':
# Example Usage
files_to_archive = ["file1.txt", "file2.csv", "nonexistent_file.txt"]
archive_file = "my_archive.tar"
archive_files(files_to_archive, archive_file)
Add your comment