{count, plural, one {कोर्स} other {कोर्स}}
Zip फ़ाइलों के साथ काम करने के लिए पूर्वापेक्षाएँ
- Python में फ़ाइल हैंडलिंग पता होनी चाहिए ताकि आप Zip फ़ाइल हैंडलिंग समझ सकें। यदि आपको फ़ाइल हैंडलिंग नहीं आती, तो सीखने के लिए W3Schools के File Handling सेक्शन पर जाएँ।
- Python में OOPS की अवधारणा
- Python की अवधारणाएँ जैसे conditionals, loops, functions, classes आदि
- यदि आप Python नहीं जानते हैं, तो DataCamp का निःशुल्क Intro to Python for Data Science कोर्स करके Python भाषा सीखें या Python का आधिकारिक documentation पढ़ें।
मैंने आगे जिन भी Zip फ़ोल्डरों का उपयोग किया है, उन्हें डाउनलोड करने के लिए यह लिंक खोलें।
Zip फ़ाइल क्या है?
Zip एक आर्काइव फ़ाइल फ़ॉर्मेट है जो lossless डेटा कंप्रेशन को सपोर्ट करता है। Zip फ़ाइल एकल फ़ाइल होती है जिसमें एक या अधिक संकुचित फ़ाइलें होती हैं।
Zip फ़ाइल के उपयोग
- Zip फ़ाइलें आपको सभी संबंधित फ़ाइलों को एक जगह रखने में मदद करती हैं।
- Zip फ़ाइलें डेटा का आकार घटाने में सहायक होती हैं।
- कई कनेक्शनों पर Zip फ़ाइलें एकल फ़ाइल के मुकाबले तेज़ी से ट्रांसफ़र होती हैं।
zipfile मॉड्यूल
zipfile मॉड्यूल की सभी methods और classes को dir() method से एक्सप्लोर करें। zipfile मॉड्यूल की सभी classes और methods पाने के लिए यह कोड देखें।
import zipfile # importing the 'zipfile' module
print(dir(zipfile))
['BZIP2_VERSION', 'BadZipFile', 'BadZipfile', 'DEFAULT_VERSION', 'LZMACompressor', 'LZMADecompressor', 'LZMA_VERSION', 'LargeZipFile', 'MAX_EXTRACT_VERSION', 'PyZipFile', 'ZIP64_LIMIT', 'ZIP64_VERSION', 'ZIP_BZIP2', 'ZIP_DEFLATED', 'ZIP_FILECOUNT_LIMIT', 'ZIP_LZMA', 'ZIP_MAX_COMMENT', 'ZIP_STORED', 'ZipExtFile', 'ZipFile', 'ZipInfo', '_CD64_CREATE_VERSION', '_CD64_DIRECTORY_RECSIZE', '_CD64_DIRECTORY_SIZE', '_CD64_DISK_NUMBER', '_CD64_DISK_NUMBER_START', '_CD64_EXTRACT_VERSION', '_CD64_NUMBER_ENTRIES_THIS_DISK', '_CD64_NUMBER_ENTRIES_TOTAL', '_CD64_OFFSET_START_CENTDIR', '_CD64_SIGNATURE', '_CD_COMMENT_LENGTH', '_CD_COMPRESSED_SIZE', '_CD_COMPRESS_TYPE', '_CD_CRC', '_CD_CREATE_SYSTEM', '_CD_CREATE_VERSION', '_CD_DATE', '_CD_DISK_NUMBER_START', '_CD_EXTERNAL_FILE_ATTRIBUTES', '_CD_EXTRACT_SYSTEM', '_CD_EXTRACT_VERSION', '_CD_EXTRA_FIELD_LENGTH', '_CD_FILENAME_LENGTH', '_CD_FLAG_BITS', '_CD_INTERNAL_FILE_ATTRIBUTES', '_CD_LOCAL_HEADER_OFFSET', '_CD_SIGNATURE', '_CD_TIME', '_CD_UNCOMPRESSED_SIZE', '_ECD_COMMENT', '_ECD_COMMENT_SIZE', '_ECD_DISK_NUMBER', '_ECD_DISK_START', '_ECD_ENTRIES_THIS_DISK', '_ECD_ENTRIES_TOTAL', '_ECD_LOCATION', '_ECD_OFFSET', '_ECD_SIGNATURE', '_ECD_SIZE', '_EndRecData', '_EndRecData64', '_FH_COMPRESSED_SIZE', '_FH_COMPRESSION_METHOD', '_FH_CRC', '_FH_EXTRACT_SYSTEM', '_FH_EXTRACT_VERSION', '_FH_EXTRA_FIELD_LENGTH', '_FH_FILENAME_LENGTH', '_FH_GENERAL_PURPOSE_FLAG_BITS', '_FH_LAST_MOD_DATE', '_FH_LAST_MOD_TIME', '_FH_SIGNATURE', '_FH_UNCOMPRESSED_SIZE', '_SharedFile', '_Tellable', '_ZipDecrypter', '_ZipWriteFile', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_check_compression', '_check_zipfile', '_get_compressor', '_get_decompressor', 'binascii', 'bz2', 'compressor_names', 'crc32', 'error', 'importlib', 'io', 'is_zipfile', 'lzma', 'main', 'os', 're', 'shutil', 'sizeCentralDir', 'sizeEndCentDir', 'sizeEndCentDir64', 'sizeEndCentDir64Locator', 'sizeFileHeader', 'stat', 'stringCentralDir', 'stringEndArchive', 'stringEndArchive64', 'stringEndArchive64Locator', 'stringFileHeader', 'struct', 'structCentralDir', 'structEndArchive', 'structEndArchive64', 'structEndArchive64Locator', 'structFileHeader', 'sys', 'threading', 'time', 'zlib']
आपने बहुत सी classes और methods देखीं। लेकिन आपको सब नहीं सीखना है। आप केवल कुछ classes और methods सीखेंगे जिनसे Zip files के साथ काम हो सके।
आइए कुछ उपयोगी Exceptions, Classes और Methods संक्षेप में देखते हैं।
Exceptions
Exception एक संदेश होता है जो आपकी मनचाही तरह से सटीक त्रुटि दिखाने के लिए इस्तेमाल किया जाता है। Python में आप त्रुटि हैंडलिंग के लिए try, except, finally कीवर्ड्स का उपयोग करते हैं।
यदि आप त्रुटि हैंडलिंग से परिचित नहीं हैं, तो सीखने के लिए Python के Error Handling दस्तावेज़ पर जाएँ।
चलिए zipfile मॉड्यूल में सभी exceptions देखते हैं।
zipfile.BadZipFile
zipfile.BadZipFile zipfile मॉड्यूल में एक exception है। यह त्रुटि खराब Zip फ़ाइलों के लिए उठती है। नीचे उदाहरण देखें।
## zipfile.BadZipFile
import zipfile
def main():
try:
with zipfile.ZipFile('sample_file.zip') as file: # opening the zip file using 'zipfile.ZipFile' class
print("Ok")
except zipfile.BadZipFile: # if the zip file has any errors then it prints the error message which you wrote under the 'except' block
print('Error: Zip file is corrupted')
if __name__ == '__main__': main()
## I used a badfile for the test
Ok
zipfile.LargeZipFile
मान लें कि आप बड़ी Zip फ़ाइल के साथ काम करना चाहते हैं, तो ZIP64 फ़ंक्शनैलिटी को Zip खोलते समय सक्षम करना होगा। यदि आप इसे सक्षम नहीं करते, तो LargeZipFile उठेगा। उदाहरण देखें।
## zipfile.LargeZipFile
## Without enabling 'Zip64'
import zipfile
def main():
try:
with zipfile.ZipFile('sample_file.zip') as file:
print('File size is compatible')
except zipfile.LargeZipFile: # it raises an 'LargeZipFile' error because you didn't enable the 'Zip64'
print('Error: File size if too large')
if __name__ == '__main__': main()
File size is compatible
## zipfile.LargeZipFile
## With enabling 'ZIP64'
import zipfile
def main():
try:
with zipfile.ZipFile('sample_file.zip', mode = 'r', allowZip64 = True) as file: # here enabling the 'Zip64'
print('File size is compatible')
except zipfile.LargeZipFile:
print('Error: File size if too large') # if the file size is too large to open it prints the error you have written
if __name__ == '__main__': main()
File size is compatible
Exception हैंडलिंग के लिए उपयुक्त Zip फ़ाइल चुनें और फिर प्रोग्राम चलाने की कोशिश करें। आपको स्पष्ट समझ मिल जाएगी।
Classes
सरल शब्दों में, class methods और attributes का समूह होती है। आप class के instances बनाकर जहाँ चाहें उसकी methods और attributes का उपयोग कर सकते हैं।
आइए zipfile मॉड्यूल की कुछ classes देखते हैं।
zipfile.ZipFile
Zip Files के साथ काम करने के लिए सबसे सामान्य class ZipFile है।
zipfile.ZipFile का उपयोग Zip फ़ाइलें लिखने और पढ़ने के लिए होता है। इसमें कुछ methods होती हैं जो Zip फ़ाइलों को संभालने में काम आती हैं।
अब, dir() ऑब्जेक्ट्स के जरिए ZipFile class की methods एक्सप्लोर करें। कोड देखें।
import zipfile
print(dir(zipfile.ZipFile)) # accessing the 'ZipFile' class
['_RealGetContents', '__class__', '__del__', '__delattr__', '__dict__', '__dir__', '__doc__', '__enter__', '__eq__', '__exit__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_extract_member', '_fpclose', '_open_to_write', '_sanitize_windows_name', '_windows_illegal_name_trans_table', '_write_end_record', '_writecheck', 'close', 'comment', 'extract', 'extractall', 'fp', 'getinfo', 'infolist', 'namelist', 'open', 'printdir', 'read', 'setpassword', 'testzip', 'write', 'writestr']
आपने पहले के उदाहरणों में zipfile.ZipFile class का उपयोग Zip फ़ाइलें पढ़ने के लिए किया है।
zipfile.ZipFile में extract, open, getinfo, setpassword आदि जैसी कई methods होती हैं, जिनसे Zip files पर काम किया जाता है।
आइए ZipFile class की कुछ methods देखते हैं।
## zipfile.ZipFile
import zipfile
def main():
with zipfile.ZipFile('sample_file.zip') as file:
# ZipFile.infolist() returns a list containing all the members of an archive file
print(file.infolist())
# ZipFile.namelist() returns a list containing all the members with names of an archive file
print(file.namelist())
# ZipFile.getinfo(path = filepath) returns the information about a member of Zip file.
# It raises a KeyError if it doesn't contain the mentioned file
print(file.getinfo(file.namelist()[-1]))
# ZipFile.open(path = filepath, mode = mode_type, pwd = password) opens the members of an archive file
# 'pwd' is optional -> if it has password mention otherwise leave it
text_file = file.open(name = file.namelist()[-1], mode = 'r')
# 'read()' method of the file prints all the content of the file. You see this method in file handling.
print(text_file.read())
# You must close the file if you don't open a file using 'with' keyword
# 'close()' method is used to close the file
text_file.close()
# ZipFile.extractall(path = filepath, pwd = password) extracts all the files to current directory
file.extractall()
# after executing check the directory to see extracted files
if __name__ == '__main__': main()
[<ZipInfo filename='extra_file.txt' filemode='-rw-rw-rw-' file_size=59>, <ZipInfo filename='READ ME.txt' filemode='-rw-rw-rw-' file_size=59>, <ZipInfo filename='even_odd.py' filemode='-rw-rw-rw-' file_size=129>]
['extra_file.txt', 'READ ME.txt', 'even_odd.py']
<ZipInfo filename='even_odd.py' filemode='-rw-rw-rw-' file_size=129>
b"num = int(input('Enter a Number:- '))\r\nif num % 2 == 0:\r\n\tprint('{} is Even'.fromat(num))\r\nelse:\r\n\tprint('{} is Odd'.fromat(num))"
यदि आप ZipFile class की सभी methods सीखना चाहते हैं, तो जिस method के बारे में जानना है, उस पर help() फ़ंक्शन का उपयोग करें।
या सीखने के लिए Python के आधिकारिक documentation पर जाएँ।
zipfile.ZipInfo
zipfile.ZipInfo class का उपयोग Zip फ़ोल्डर के किसी सदस्य का प्रतिनिधित्व करने के लिए होता है।
पहले dir() method का उपयोग करके zipfile.ZipInfo class के सभी ऑब्जेक्ट्स एक्सप्लोर करें। नीचे कोड देखें।
## zipfile.ZipInfo
import zipfile
print(dir(zipfile.ZipInfo))
['CRC', 'FileHeader', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__slots__', '__str__', '__subclasshook__', '_decodeExtra', '_encodeFilenameFlags', '_raw_time', 'comment', 'compress_size', 'compress_type', 'create_system', 'create_version', 'date_time', 'external_attr', 'extra', 'extract_version', 'file_size', 'filename', 'flag_bits', 'from_file', 'header_offset', 'internal_attr', 'is_dir', 'orig_filename', 'reserved', 'volume']
अब आप zipfile.ZipInfo class की कुछ methods देखने जा रहे हैं।
## zipfile.ZipInfo
import zipfile
def main():
with zipfile.ZipFile('sample_file.zip') as file:
# 'infolist()' is the object of 'ZipFile' class
# 'infolist()' returns a list containing all the folders and files of the zip -> 'ZipInfo' objects
# assigning last element of the list to a variable to test all the methods of 'ZipInfo'
archive = file.infolist()
read_me_file = archive[-1]
# 'ZipInfo' methods
# ZipInfo_object.filename returns the name of the file
print("Name of the file:- {}".format(read_me_file.filename))
# ZipInfo_object.file_size returns the size of the file
print("Size of the file:- {}".format(read_me_file.file_size))
# ZipInfo_object.is_dir() returns True if it's directory otherwise False
print("Is directory:- {}".format(read_me_file.is_dir()))
# ZipInfo_object.date_time() returns the created date & time of file
print("File created data & time:- {}".format(read_me_file.date_time))
if __name__ == '__main__': main()
Name of the file:- sample_file/READ ME.txt
Size of the file:- 59
Is directory:- False
File created data & time:- (2018, 10, 4, 11, 32, 22)
यदि आप ZipInfo के ऑब्जेक्ट्स के बारे में अधिक जानना चाहते हैं, तो ZipInfo पर जाएँ।
Methods
Methods प्रोग्राम में किसी विशिष्ट कार्यक्षमता के लिए कोड का ब्लॉक होती हैं। उदाहरण के लिए, यदि आप किसी संख्या का परिमान मान निकालना चाहते हैं, तो आप Python की method abs का उपयोग कर सकते हैं।
आप इसे जहाँ चाहें उपयोग कर सकते हैं। आइए zipfile मॉड्यूल की कुछ methods देखते हैं।
zipfile.is_zipfile()
is_zipfile(filename) method zipfile मॉड्यूल की है, जो फ़ाइल वैध Zip हो तो True लौटाती है, अन्यथा False।
उदाहरण देखें।
## zipfile.is_zip(filename)
import zipfile
def main():
print(zipfile.is_zipfile('sample_file.zip')) # it returns True
if __name__ == '__main__': main()
True
Zip फ़ाइलों को संभालना
इस सेक्शन में, आप सीखेंगे कि Zip फ़ाइलों को कैसे संभालें जैसे खोलना, निकालना, लिखना आदि।
Zip फ़ाइल निकालना
extractall method का उपयोग करके Zip फ़ाइल की फ़ाइलों को वर्तमान डायरेक्टरी में निकाला जाता है।
## extracting zip file
import zipfile
def main():
# assigning filename to a variable
file_name = 'sample_file.zip'
# opening Zip using 'with' keyword in read mode
with zipfile.ZipFile(file_name, 'r') as file:
# printing all the information of archive file contents using 'printdir' method
print(file.printdir())
# extracting the files using 'extracall' method
print('Extracting all files...')
file.extractall()
print('Done!') # check your directory of zip file to see the extracted files
if __name__ == '__main__': main()
File Name Modified Size
sample_file/ 2018-10-04 11:33:22 0
sample_file/even_odd.py 2018-06-29 23:35:54 129
sample_file/READ ME.txt 2018-10-04 11:32:22 59
None
Extracting all files...
Done!
पासवर्ड के साथ Zip निकालना
किसी Zip को पासवर्ड के साथ निकालने के लिए, आपको extract(pwd = password) या extractall(pwd = password) methods के pwd positional argument को मान देना होगा।
आपको पासवर्ड bytes में पास करना होगा। str को bytes में बदलने के लिए Python की built-in method bytes का utf-8 एन्कोड फ़ॉर्मेट के साथ उपयोग करें।
उदाहरण देखें।
## extracting zip with password
import zipfile
def main():
file_name = 'pswd_file.zip'
pswd = 'datacamp'
with zipfile.ZipFile(file_name) as file:
# password you pass must be in the bytes you converted 'str' into 'bytes'
file.extractall(pwd = bytes(pswd, 'utf-8'))
if __name__ == '__main__': main()
आप ZipFile class की setpassword(pwd = password) method का उपयोग करके भी फ़ाइलें निकाल सकते हैं। नीचे उदाहरण देखें।
## extracting zip with password
import zipfile
def main():
file_name = 'pswd_file.zip'
pswd = 'datacamp'
with zipfile.ZipFile(file_name) as file:
# 'setpassword' method is used to give a password to the 'Zip'
file.setpassword(pwd = bytes(pswd, 'utf-8'))
file.extractall()
if __name__ == '__main__': main()
Zip फ़ाइलें बनाना
Zip फ़ाइल बनाने के लिए आपको किसी अतिरिक्त method की ज़रूरत नहीं है। बस नाम को ZipFile class को पास करें, और यह वर्तमान डायरेक्टरी में एक आर्काइव बना देगा।
नीचे उदाहरण देखें।
## Creating Zip file
import zipfile
def main():
archive_name = 'example_file.zip'
# below one line of code will create a 'Zip' in the current working directory
with zipfile.ZipFile(archive_name, 'w') as file:
print("{} is created.".format(archive_name))
if __name__ == '__main__': main()
example_file.zip is created.
Zip फ़ाइलों में लिखना
आर्काइव फ़ाइल में फ़ाइलें लिखने के लिए आपको Zip फ़ाइल को write मोड में खोलना होगा। यह Zip में मौजूद सभी फ़ाइलों को ओवरराइट कर देता है।
आइए एक उदाहरण देखें।
## Writing files to zip
import zipfile
def main():
file_name = 'sample_file.zip'
# Opening the 'Zip' in writing mode
with zipfile.ZipFile(file_name, 'w') as file:
# write mode overrides all the existing files in the 'Zip.'
# you have to create the file which you have to write to the 'Zip.'
file.write('extra_file.txt')
print('File overrides the existing files')
# opening the 'Zip' in reading mode to check
with zipfile.ZipFile(file_name, 'r') as file:
print(file.namelist())
if __name__ == '__main__': main()
File overrides the existing files
['extra_file.txt']
Zip में फ़ाइलें जोड़ना
Zip में कोई फ़ाइल जोड़ने के लिए आपको उसे append(a) मोड में खोलना होगा। यह मौजूद फ़ाइलों को ओवरराइट नहीं करता।
उदाहरण देखें।
## Appending files to zip
import zipfile
def main():
file_name = 'sample_file.zip'
# opening the 'Zip' in writing mode
with zipfile.ZipFile(file_name, 'a') as file:
# append mode adds files to the 'Zip'
# you have to create the files which you have to add to the 'Zip'
file.write('READ ME.txt')
file.write('even_odd.py')
print('Files added to the Zip')
# opening the 'Zip' in reading mode to check
with zipfile.ZipFile(file_name, 'r') as file:
print(file.namelist())
if __name__ == '__main__': main()
Files added to the Zip
['extra_file.txt', 'READ ME.txt', 'even_odd.py']
अब तक, आपने सीखा कि Zip फ़ाइलों को कैसे संभालना है। अब आप Zip फ़ाइलों को खोल, लिख, जोड़, निकाल, बना आदि सकते हैं। अब आप एक सरल प्रोग्राम लिखने जा रहे हैं।
आइए देखें वह क्या है?
Loops और zipfile का उपयोग करके पासवर्ड वाले कई सब-ज़िप्स निकालना
- आपके पास एक Zip है जिसमें गहराई में कुछ सब Zip फ़ाइलें हैं। और प्रत्येक Zip फ़ाइल का पासवर्ड उसका नाम है। हमारा कार्य है कि अंत तक पहुँचने तक सभी Zip फ़ाइलों को अनज़िप करें।
समस्या सुलझाने के चरण
- Parent फ़ाइल को उसके नाम को पासवर्ड मानकर निकालें।
- namelist() method से पहला child नाम लें। उसे किसी वेरिएबल में रखें।
-
अनंत बार के लिए loop चलाएँ।
-
is_zipfile() method से जाँचें कि फ़ाइल Zip है या नहीं। यदि हाँ, तो निम्न करें।
-
name वेरिएबल के साथ zip खोलें।
-
name वेरिएबल से Zip का पासवर्ड लें।
-
Zip निकालें।
-
अगले Zip का नाम लेकर उसे name वेरिएबल में सहेजें।
-
-
अन्यथा
- break का उपयोग करके loop तोड़ दें।
-
मैंने ऊपर प्रक्रिया बनाई है। आप चाहें तो अपनी फ़ाइलों की व्यवस्था के अनुसार इसे बदल सकते हैं।
## Solution
import zipfile
def main():
# storing the parent name
parent_file_name = '000.zip'
with zipfile.ZipFile(parent_file_name, 'r') as parent_file:
# extracting the parent file
pswd = bytes(parent_file_name.split('.')[0], 'utf-8')
parent_file.extractall(pwd = pswd)
# getting the first child
next_zip_name = parent_file.namelist()[0]
# looping through the sub zips infinite times until you don't encouter a 'Zip' file
while True:
if zipfile.is_zipfile(next_zip_name):
# opening the zip
with zipfile.ZipFile(next_zip_name, 'r') as child_file:
# getting password from the zip name
pswd = bytes(next_zip_name.split('.')[0], 'utf-8')
# extracting the zip
child_file.extractall(pwd = pswd)
# getting the child zip name
next_zip_name = child_file.namelist()[0]
else:
break
if __name__ == '__main__': main()
ऊपर का प्रोग्राम चलाने के बाद, आप देखेंगे कि सभी सब-ज़िप्स वर्तमान डायरेक्टरी में निकाल दिए गए हैं।
समापन
ट्यूटोरियल पूरा करने पर बधाई!
आशा है आपको यह ट्यूटोरियल पसंद आया होगा। यह लेख Zip फ़ाइलों के साथ काम करते समय आपके लिए काफी मददगार होगा। अब आप Zip फ़ाइलों के साथ काम करने में सक्षम हैं।
यदि लेख के बारे में आपके कोई सवाल हैं, तो टिप्पणी अनुभाग में पूछें। मैं यथाशीघ्र उत्तर दूँगा।
फिर से, यदि आप Python में नए हैं, तो DataCamp का निःशुल्क Intro to Python for Data Science कोर्स करें या Python का आधिकारिक documentation पढ़ें।
Happy Coding!