logo

العمل مع الملفات المضغوطة في بايثون

تشرح هذه المقالة كيف يمكن إجراء عمليات مختلفة على ملف مضغوط باستخدام برنامج بايثون بسيط. ما هو الملف المضغوط؟ ZIP هو تنسيق ملف أرشيف يدعم ضغط البيانات بدون فقدان البيانات. نعني بالضغط بدون فقدان أن خوارزمية الضغط تسمح بإعادة بناء البيانات الأصلية بشكل مثالي من البيانات المضغوطة. لذا فإن الملف المضغوط هو ملف واحد يحتوي على ملف مضغوط واحد أو أكثر مما يوفر طريقة مثالية لتصغير الملفات الكبيرة والاحتفاظ بالملفات المرتبطة معًا. لماذا نحتاج إلى ملفات مضغوطة؟
  • لتقليل متطلبات التخزين.
  • لتحسين سرعة النقل عبر الاتصالات القياسية.
للعمل على الملفات المضغوطة باستخدام لغة بايثون، سنستخدم وحدة بايثون مدمجة تسمى com.zipfile .

1. استخراج ملف مضغوط

Python
# importing required modules from zipfile import ZipFile # specifying the zip file name file_name = 'my_python_files.zip' # opening the zip file in READ mode with ZipFile(file_name 'r') as zip: # printing all the contents of the zip file zip.printdir() # extracting all the files print('Extracting all the files now...') zip.extractall() print('Done!') 
The above program extracts a zip file named 'my_python_files.zip' in the same directory as of this python script. The output of above program may look like this: العمل مع الملفات المضغوطة في بايثون' title=دعونا نحاول فهم الكود أعلاه على شكل أجزاء:
  • from zipfile import ZipFile
    ZipFile is a class of zipfile module for reading and writing zip files. Here we import only class ZipFile from zipfile module.
  • with ZipFile(file_name 'r') as zip:
    Here a ZipFile object is made by calling ZipFile constructor which accepts zip file name and mode parameters. We create a ZipFile object in يقرأ الوضع وتسميته باسم أَزِيز .
  • zip.printdir()
    برينتدير() تقوم الطريقة بطباعة جدول محتويات للأرشيف.
  • zip.extractall()
    استخراج الكل () ستقوم الطريقة باستخراج جميع محتويات الملف المضغوط إلى دليل العمل الحالي. يمكنك أيضًا الاتصال يستخرج() method to extract any file by specifying its path in the zip file. For example:
    zip.extract('python_files/python_wiki.txt')
    This will extract only the specified file. If you want to read some specific file you can go like this:
    data = zip.read(name_of_file_to_read)

2. الكتابة إلى ملف مضغوط

فكر في دليل (مجلد) بهذا التنسيق: العمل مع الملفات المضغوطة في بايثون' title= Here we will need to crawl the whole directory and its sub-directories in order to get a list of all file paths before writing them to a zip file. The following program does this by crawling the directory to be zipped: Python
# importing required modules from zipfile import ZipFile import os def get_all_file_paths(directory): # initializing empty file paths list file_paths = [] # crawling through directory and subdirectories for root directories files in os.walk(directory): for filename in files: # join the two strings in order to form the full filepath. filepath = os.path.join(root filename) file_paths.append(filepath) # returning all file paths return file_paths def main(): # path to folder which needs to be zipped directory = './python_files' # calling function to get all file paths in the directory file_paths = get_all_file_paths(directory) # printing the list of all files to be zipped print('Following files will be zipped:') for file_name in file_paths: print(file_name) # writing files to a zipfile with ZipFile('my_python_files.zip''w') as zip: # writing each file one by one for file in file_paths: zip.write(file) print('All files zipped successfully!') if __name__ == '__main__': main() 
The output of above program looks like this: العمل مع الملفات المضغوطة في بايثون' title=دعونا نحاول فهم الكود أعلاه من خلال تقسيمه إلى أجزاء:
  • def get_all_file_paths(directory): file_paths = [] for root directories files in os.walk(directory): for filename in files: filepath = os.path.join(root filename) file_paths.append(filepath) return file_paths
    First of all to get all file paths in our directory we have created this function which uses the نظام التشغيل. Walk()  طريقة. في كل تكرار، يتم إلحاق جميع الملفات الموجودة في هذا الدليل بقائمة تسمى file_paths . في النهاية نعيد جميع مسارات الملفات.
  • file_paths = get_all_file_paths(directory)
    Here we pass the directory to be zipped to the get_all_file_paths() وظيفة والحصول على قائمة تحتوي على كافة مسارات الملفات.
  • with ZipFile('my_python_files.zip''w') as zip:
    Here we create a ZipFile object in WRITE mode this time.
  • for file in file_paths: zip.write(file)
    Here we write all the files to the zip file one by one using يكتب طريقة.

3. الحصول على كافة المعلومات حول ملف مضغوط



Python
# importing required modules from zipfile import ZipFile import datetime # specifying the zip file name file_name = 'example.zip' # opening the zip file in READ mode with ZipFile(file_name 'r') as zip: for info in zip.infolist(): print(info.filename) print('tModified:t' + str(datetime.datetime(*info.date_time))) print('tSystem:tt' + str(info.create_system) + '(0 = Windows 3 = Unix)') print('tZIP version:t' + str(info.create_version)) print('tCompressed:t' + str(info.compress_size) + ' bytes') print('tUncompressed:t' + str(info.file_size) + ' bytes') 
The output of above program may look like this: ' title=
for info in zip.infolist():
Here قائمة المعلومات() تقوم الطريقة بإنشاء مثيل لـ ZipInfo فئة تحتوي على كافة المعلومات حول الملف المضغوط. يمكننا الوصول إلى جميع المعلومات مثل تاريخ آخر تعديل للملفات، نظام أسماء الملفات الذي تم إنشاء الملفات عليه، حجم الإصدار المضغوط من الملفات في شكل مضغوط وغير مضغوط وما إلى ذلك. تمت المساهمة في هذه المقالة بواسطة نيخيل كومار . إنشاء اختبار