In the above snippet we change permission of a file by supplying filter argument which modifies the TarInfo.mode. Tarfile provides one cool feature that we haven't seen with other modules and that is ability to modify attributes of files when they're being added to archive. To get insight about individual files we can use gettarinfo, which provides all the Linux file attributes. Next, to confirm that all the files are really there, we use getmembers method. With tarfile module we can also pass in for example symlinks or whole directories that would be recursively added. After that we add all our files to the archive. We start with the basic creation of archive, but here we use access mode "w:gz" which specifies that we want to use GZ compression. To do this, all we need to change is access mode to “append” ( "a"): In addition to creating a reading archives/files, ZIP allows us to also append files to existing archives. We see that it has the expected content, so we can go ahead and extract it to file specified by path ( /tmp/). In this example we just print the list of ZipInfo objects, but you could also inspect its attributes to get CRC, size, compression type, etc.Īfter checking all the files we open and read one of them. Before reading any files we check CRC and file headers, afterwards we retrieve information about all files present in the archive. Next, to demonstrate that it worked, we open the archive. After adding all the files, we also set archive password using setpassword method. You will notice that we didn't actually need to open the files that we're adding - all we needed to do is call write passing in the file name. In this snippet we start by creating ZIP archive using ZipFile context manager in "write" ( w) mode and then add the files to this archive. This is a fairly long piece of code, but covers all the important features of zipfile module. This is fairly low level library and therefore might not be so commonly used so let's just look at the basic compression/decompression of whole file at once: So, let’s see how we can perform these basic operations with each of them:įirst up, zlib. Some of them more basic, some of them with a lot of extra features, but what they all have in common is that they (obviously) include functions for compression. We’ve got a plenty of libraries to choose from. It also has support for other features we know from tar utility - list of those is available at the top of above linked docs page. It can read and write gzip, bz2 and lzma files or archives.
0 Comments
Leave a Reply. |