{"id":87076,"date":"2023-04-06T11:04:08","date_gmt":"2023-04-06T05:34:08","guid":{"rendered":"https:\/\/techvidvan.com\/tutorials\/?p=87076"},"modified":"2023-04-06T11:04:08","modified_gmt":"2023-04-06T05:34:08","slug":"zipping-files-with-python","status":"publish","type":"post","link":"https:\/\/techvidvan.com\/tutorials\/zipping-files-with-python\/","title":{"rendered":"Zipping Files With Python"},"content":{"rendered":"<p>In this tutorial, we will learn about Zipping Files With Python. Let&#8217;s start!!<\/p>\n<h3>Zipping Files With Python<\/h3>\n<p><span style=\"font-weight: 400\">The zipfile module in Python provides a way to work with ZIP files. It allows you to create, extract, and manipulate ZIP files in a convenient and easy-to-use manner. With the zipfile module, you can:<\/span><\/p>\n<ul>\n<li style=\"font-weight: 400\"><span style=\"font-weight: 400\">Create new ZIP files and add files to them<\/span><\/li>\n<li style=\"font-weight: 400\"><span style=\"font-weight: 400\">Extract files from existing ZIP files<\/span><\/li>\n<li style=\"font-weight: 400\"><span style=\"font-weight: 400\">Print the contents of a ZIP file<\/span><\/li>\n<li style=\"font-weight: 400\"><span style=\"font-weight: 400\">Read the contents of a file within a ZIP file<\/span><\/li>\n<li style=\"font-weight: 400\"><span style=\"font-weight: 400\">Set and read the password of a ZIP file<\/span><\/li>\n<li style=\"font-weight: 400\"><span style=\"font-weight: 400\">And other related functionalities.<\/span><\/li>\n<\/ul>\n<p>The zipfile module provides a ZipFile class that can be used to work with ZIP files. The ZipFile class provides methods like write(), extract(), extractall(), printdir(), read(), namelist(), infolist(), and close() to perform various operations on ZIP files.<\/p>\n<p>To create a new ZIP file, you can use the ZipFile class in write mode, &#8216;w&#8217;, and add files to it using the write() method. To extract files from a ZIP file, you can use the extractall() method. Also, To print the contents of a ZIP file, you can use the printdir() method.<\/p>\n<h3>zipfile modes in python<\/h3>\n<p>The zipfile module in Python provides several modes for opening and interacting with ZIP files. These modes are used when creating an instance of the ZipFile class. The following are the available modes in the zipfile module:<\/p>\n<p><span style=\"font-weight: 400\"><strong>1. &#8216;r&#8217;:<\/strong> You can read an existing ZIP file using this mode. Since it is opened in read-only mode, no changes may be made.<\/span><\/p>\n<p><span style=\"font-weight: 400\"><strong>2. &#8216;w&#8217;:<\/strong> This mode is used to write a new ZIP file or to overwrite an existing file. Any existing contents in the file will be destroyed when the file is opened in write mode.<\/span><\/p>\n<p><span style=\"font-weight: 400\"><strong>3. &#8216;a&#8217;:<\/strong> You can append to an existing ZIP file using this mode. New files can be added to the existing ZIP file when the file is opened in write mode.<\/span><\/p>\n<p><span style=\"font-weight: 400\"><strong>4. &#8216;x&#8217;:<\/strong> Only fresh ZIP files are created using this option.<\/span><\/p>\n<p><span style=\"font-weight: 400\">If the file already exists, the operation will raise a &#8220;FileExistsError&#8221;<\/span><\/p>\n<p><span style=\"font-weight: 400\">Here&#8217;s an example of how to use these modes:<\/span><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\"># reading an existing zip file\nwith zipfile.ZipFile('existing_file.zip', 'r') as zip:\n    zip.printdir()\n    \n# creating a new zip file\nwith zipfile.ZipFile('new_file.zip', 'w') as zip:\n    zip.write('file1.txt')\n    \n# appending to an existing zip file\nwith zipfile.ZipFile('existing_file.zip', 'a') as zip:\n    zip.write('file2.txt')\n    \n# creating a new zip file exclusively\nwith zipfile.ZipFile('exclusive_file.zip', 'x') as zip:\n    zip.write('file1.txt')\n<\/pre>\n<p><span style=\"font-weight: 400\">It&#8217;s crucial to remember that closing the file when you&#8217;re finished working with it is always a good practise when working with ZIP files. <\/span><span style=\"font-weight: 400\">This can be achieved by using the with statement as shown in the examples above.<\/span><\/p>\n<h3><span style=\"font-weight: 400\">zipfile methods in python<\/span><\/h3>\n<p><b>1. ZipFile.write(filename, arcname=None, compress_type=None):<\/b><\/p>\n<p><span style=\"font-weight: 400\">This method is used to add a file to the ZIP archive. The parameters filename and arcname specify the names of the files to be added and the archive, respectively. The compress_type parameter is used to specify the compression method to be used.<\/span><\/p>\n<p><b>Example:<\/b><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">    \nimport zipfile\n\n# create a new zip file\nwith zipfile.ZipFile('my_files.zip', 'w') as zip:\n    # add a file to the archive\n    zip.write('file1.txt')\n    # add a file to the archive with a different name in the archive\n    zip.write('file2.txt', 'my_file2.txt')\n    # add a file to the archive with a different compression method\n    zip.write('file3.txt', compress_type=zipfile.ZIP_DEFLATED)\n<\/pre>\n<p><b>2. ZipFile.extract(member, path=None, pwd=None): <\/b><\/p>\n<p><span style=\"font-weight: 400\">This method is used to extract a single file from the archive. The member parameter is the name of the file to be extracted, and the path parameter is the directory where the file should be extracted. The pwd parameter is used to specify a password for the archive.<\/span><\/p>\n<p><b>Example:<\/b><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import zipfile\n\n# name of zip file\nzip_name = 'my_files.zip'\n\n# open the zip file\nwith zipfile.ZipFile(zip_name, 'r') as zip:\n    # extract a single file\n    zip.extract('file1.txt')\n    # extract a single file to a specific directory\n    zip.extract('file2.txt', 'extracted_files')\n    # extract a single file with password\n    zip.extract('file3.txt', pwd=b'secret')\n<\/pre>\n<p><b>3. ZipFile.extractall(path=None, members=None, pwd=None):<\/b><\/p>\n<p><span style=\"font-weight: 400\">This method is used to extract all the files from the archive. The path parameter is the directory where the files should be extracted, the members parameter is a list of files that should be extracted, and the pwd parameter is used to specify a password for the archive.<\/span><\/p>\n<p><b>Example:<\/b><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import zipfile\n\n# name of zip file\nzip_name = 'my_files.zip'\n\n# open the zip file\nwith zipfile.ZipFile(zip_name, 'r') as zip:\n    # extract all files\n    zip.extractall()\n    # extract all files to a specific directory\n    zip.extractall(path='extracted_files')\n    # extract specific files\n    zip.extractall(members=['file1.txt', 'file2.txt'])\n    # extract all files with password\n    zip.extractall(pwd=b'secret')\n\n<\/pre>\n<p><b>4. ZipFile.printdir():<\/b><\/p>\n<p><span style=\"font-weight: 400\">This method is used to print the contents of the archive. It shows the name, size, and date of the files in the archive.<\/span><\/p>\n<p><strong>Example:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import zipfile\n\n# name of zip file\nzip_name = 'my_files.zip'\n\n# open the zip file\nwith zipfile.ZipFile(zip_name, 'r') as zip:\n    # print the contents of the archive\n    zip.printdir()\n<\/pre>\n<p><b>Output:<\/b><\/p>\n<p><span style=\"font-weight: 400\">File Name \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 Modified\u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0Size<\/span><\/p>\n<p><span style=\"font-weight: 400\">file1.txt\u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 2020-11-22 12:30:20\u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 12<\/span><\/p>\n<p><span style=\"font-weight: 400\">file2.txt\u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 2020-11-22 12:31:01\u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 23<\/span><\/p>\n<p><b>5. ZipFile.read(name, pwd=None):<\/b><\/p>\n<p><span style=\"font-weight: 400\">This approach is used to read a file&#8217;s contents from an archive.. The name parameter is the name of the file to be read, and the pwd parameter is used to specify a password for the archive.<\/span><\/p>\n<p><b>Example:<\/b><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import zipfile\n\n# name of zip file\nzip_name = 'my_files.zip'\n\n# open the zip file\nwith zipfile.ZipFile(zip_name, 'r') as zip:\n    # read the contents of a file\n    content = zip.read('file1.txt')\n    print(content)\n    # read the contents of a file with password\n    content = zip.read('file2.txt', pwd=b'secret')\n    print(content)\n<\/pre>\n<p><b>6. <\/b><b>ZipFile.namelist(): <\/b><\/p>\n<p><span style=\"font-weight: 400\">This method returns a list of all the files in the archive.<\/span><\/p>\n<p><b>Example:<\/b><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import zipfile\n\n# name of zip file\nzip_name = 'my_files.zip'\n\n# open the zip file\nwith zipfile.ZipFile(zip_name, 'r') as zip:\n    # get a list of the names of the files in the archive\n    files = zip.namelist()\n    print(files)\n\n<\/pre>\n<p><b>7. ZipFile.infolist(): <\/b><\/p>\n<p><span style=\"font-weight: 400\">This function provides a list of ZipInfo objects, which include details like the file&#8217;s name, size, and date about each item in the archive.<\/span><\/p>\n<p><b>Example:<\/b><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import zipfile\n\n# name of zip file\nzip_name = 'my_files.zip'\n\n# open the zip file\nwith zipfile.ZipFile(zip_name, 'r') as zip:\n    # get a list of `ZipInfo` objects\n    files_info = zip.infolist()\n    for file in files_info:\n        print(file.filename)\n        print(file.file_size)\n        print(file.date_time)\n<\/pre>\n<p><b>8. ZipFile.close(): <\/b><\/p>\n<p><span style=\"font-weight: 400\">When you&#8217;re through with an archive, you can close it using this technique.<\/span><\/p>\n<p><b>Example:<\/b><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import zipfile\n\n# name of zip file\nzip_name = 'my_files.zip'\n\n# open the zip file\nwith zipfile.ZipFile(zip_name, 'r') as zip:\n    # perform operations on the archive\n    zip.extractall()\n    # close the archive\n    zip.close()\n<\/pre>\n<h3><strong>Conclusion<\/strong><\/h3>\n<p><span style=\"font-weight: 400\">In summary, the zipfile module in Python provides a powerful and easy-to-use interface for working with ZIP files. It allows you to perform a wide range of operations on ZIP files, making it a valuable tool for any Python developer.<\/span><\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this tutorial, we will learn about Zipping Files With Python. Let&#8217;s start!! Zipping Files With Python The zipfile module in Python provides a way to work with ZIP files. It allows you to&#46;&#46;&#46;<\/p>\n","protected":false},"author":1,"featured_media":87368,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1053],"tags":[4923],"class_list":["post-87076","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-python","tag-zipping-files-with-python"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.7 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Zipping Files With Python - TechVidvan<\/title>\n<meta name=\"description\" content=\"zipfile module in Python provides a powerful and easy-to-use interface for working with ZIP files. See the various modes and methods.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/techvidvan.com\/tutorials\/zipping-files-with-python\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Zipping Files With Python - TechVidvan\" \/>\n<meta property=\"og:description\" content=\"zipfile module in Python provides a powerful and easy-to-use interface for working with ZIP files. See the various modes and methods.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/techvidvan.com\/tutorials\/zipping-files-with-python\/\" \/>\n<meta property=\"og:site_name\" content=\"TechVidvan\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/TechVidvan\/\" \/>\n<meta property=\"article:published_time\" content=\"2023-04-06T05:34:08+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2023\/04\/zipping-files-with-python.webp\" \/>\n\t<meta property=\"og:image:width\" content=\"1200\" \/>\n\t<meta property=\"og:image:height\" content=\"628\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/webp\" \/>\n<meta name=\"author\" content=\"TechVidvan Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:site\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"TechVidvan Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"5 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Zipping Files With Python - TechVidvan","description":"zipfile module in Python provides a powerful and easy-to-use interface for working with ZIP files. See the various modes and methods.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/techvidvan.com\/tutorials\/zipping-files-with-python\/","og_locale":"en_US","og_type":"article","og_title":"Zipping Files With Python - TechVidvan","og_description":"zipfile module in Python provides a powerful and easy-to-use interface for working with ZIP files. See the various modes and methods.","og_url":"https:\/\/techvidvan.com\/tutorials\/zipping-files-with-python\/","og_site_name":"TechVidvan","article_publisher":"https:\/\/www.facebook.com\/TechVidvan\/","article_published_time":"2023-04-06T05:34:08+00:00","og_image":[{"width":1200,"height":628,"url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2023\/04\/zipping-files-with-python.webp","type":"image\/webp"}],"author":"TechVidvan Team","twitter_card":"summary_large_image","twitter_creator":"@vidvantech","twitter_site":"@vidvantech","twitter_misc":{"Written by":"TechVidvan Team","Est. reading time":"5 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/techvidvan.com\/tutorials\/zipping-files-with-python\/#article","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/zipping-files-with-python\/"},"author":{"name":"TechVidvan Team","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22"},"headline":"Zipping Files With Python","datePublished":"2023-04-06T05:34:08+00:00","mainEntityOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/zipping-files-with-python\/"},"wordCount":750,"commentCount":0,"publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/zipping-files-with-python\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2023\/04\/zipping-files-with-python.webp","keywords":["Zipping Files With Python"],"articleSection":["Python Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/techvidvan.com\/tutorials\/zipping-files-with-python\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/techvidvan.com\/tutorials\/zipping-files-with-python\/","url":"https:\/\/techvidvan.com\/tutorials\/zipping-files-with-python\/","name":"Zipping Files With Python - TechVidvan","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/#website"},"primaryImageOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/zipping-files-with-python\/#primaryimage"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/zipping-files-with-python\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2023\/04\/zipping-files-with-python.webp","datePublished":"2023-04-06T05:34:08+00:00","description":"zipfile module in Python provides a powerful and easy-to-use interface for working with ZIP files. See the various modes and methods.","breadcrumb":{"@id":"https:\/\/techvidvan.com\/tutorials\/zipping-files-with-python\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/techvidvan.com\/tutorials\/zipping-files-with-python\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/zipping-files-with-python\/#primaryimage","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2023\/04\/zipping-files-with-python.webp","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2023\/04\/zipping-files-with-python.webp","width":1200,"height":628,"caption":"zipping files with python"},{"@type":"BreadcrumbList","@id":"https:\/\/techvidvan.com\/tutorials\/zipping-files-with-python\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/techvidvan.com\/tutorials\/"},{"@type":"ListItem","position":2,"name":"Zipping Files With Python"}]},{"@type":"WebSite","@id":"https:\/\/techvidvan.com\/tutorials\/#website","url":"https:\/\/techvidvan.com\/tutorials\/","name":"TechVidvan Blogs","description":"","publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/techvidvan.com\/tutorials\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/techvidvan.com\/tutorials\/#organization","name":"TechVidvan","url":"https:\/\/techvidvan.com\/tutorials\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","width":200,"height":50,"caption":"TechVidvan"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/TechVidvan\/","https:\/\/x.com\/vidvantech"]},{"@type":"Person","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22","name":"TechVidvan Team","description":"The TechVidvan Team delivers practical, beginner-friendly tutorials on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our experts are here to help you upskill and excel in today\u2019s tech industry."}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/87076","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/comments?post=87076"}],"version-history":[{"count":0,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/87076\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media\/87368"}],"wp:attachment":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media?parent=87076"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/categories?post=87076"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/tags?post=87076"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}