1. import os
  2. import tarfile
  3. def archive_files(file_list, archive_name):
  4. """
  5. Archives the content of a list of files into a tar archive.
  6. Args:
  7. file_list (list): A list of file paths to archive.
  8. archive_name (str): The name of the tar archive to create.
  9. """
  10. try:
  11. with tarfile.open(archive_name, "w") as tar:
  12. for file_path in file_list:
  13. if os.path.exists(file_path):
  14. tar.add(file_path, arcname=os.path.basename(file_path)) # Add file to archive, preserving name
  15. else:
  16. print(f"Warning: File not found: {file_path}")
  17. print(f"Successfully created archive: {archive_name}")
  18. except Exception as e:
  19. print(f"Error creating archive: {e}")
  20. if __name__ == '__main__':
  21. # Example Usage
  22. files_to_archive = ["file1.txt", "file2.csv", "nonexistent_file.txt"]
  23. archive_file = "my_archive.tar"
  24. archive_files(files_to_archive, archive_file)

Add your comment