English 中文(简体)
从 Python 的 zip 文件中移除自动生成的 __MACOSX 文件夹
原标题:Remove auto-generated __MACOSX folder from inside a zip file in Python
I have zip files uploaded by clients through a web server that sometimes contain pesky __MACOSX directories inside that gum things up. How can I remove these? I thought of using ZipFile, but this answer says that isn t possible and gives this suggestion: Read out the rest of the archive and write it to a new zip file. How can I do this with ZipFile? Another Python based alternative like shutil or something similar would also be fine.
最佳回答
The examples below are designed to determine if a __MACOSX file is contained within a zip file. If this pesky exist then a new zip archive is created and all the files that are not __MACOSX files are written to this new archive. This code can be extended to include .ds_store files. Please let me if you need to delete the old zip file and replace it with the new clean zip file. Hopefully, these answers help you solve your issue. Example One from zipfile import ZipFile original_zip = ZipFile ( original.zip , r ) new_zip = ZipFile ( new_archve.zip , w ) for item in original_zip.infolist(): buffer = original_zip.read(item.filename) if not str(item.filename).startswith( __MACOSX/ ): new_zip.writestr(item, buffer) new_zip.close() original_zip.close() Example Two def check_archive_for_bad_filename(file): zip_file = ZipFile(file, r ) for filename in zip_file.namelist(): print(filename) if filename.startswith( __MACOSX/ ): return True def remove_bad_filename_from_archive(original_file, temporary_file): zip_file = ZipFile(original_file, r ) for item in zip_file.namelist(): buffer = zip_file.read(item) if not item.startswith( __MACOSX/ ): if not os.path.exists(temporary_file): new_zip = ZipFile(temporary_file, w ) new_zip.writestr(item, buffer) new_zip.close() else: append_zip = ZipFile(temporary_file, a ) append_zip.writestr(item, buffer) append_zip.close() zip_file.close() archive_filename = old.zip temp_filename = new.zip results = check_archive_for_bad_filename(archive_filename) if results: print( Removing MACOSX file from archive. ) remove_bad_filename_from_archive(archive_filename, temp_filename) else: print( No MACOSX file in archive. )
问题回答
The idea would be to use ZipFile to extract the contents into some defined folder then remove the __MACOSX entry (os.rmdir, os.remove) and then compress it again. Depending if you have zip command on your OS you might be able to skip the re-compressing part. You could as well control this command from python by using os.system or subprocess module.
Here are some steps I took to work around a solution for the annoying macOS problem. Open your shell configuration file (like .bashrc or .zshrc). For example: nano ~/.bashrc Add the following function at the end of the file: zipar() { if [ "$#" -ne 2 ]; then echo "Usage: zipar " return 1 fi zip -r "$1" "$2" -x "*.DS_Store" -x "__MACOSX" } Save the file and exit the editor (in nano, use Ctrl+O to save and Ctrl+X to exit). Reload the terminal to apply the changes: Now you can use the zipar command in your terminal to create .zip files, excluding .DS_Store and __MACOSX, by specifying the name of the .zip file and the path to the folder. For example: zipar my_compressed_file.zip path/to/folder This will create a my_compressed_file.zip in the specified directory, that s it. Important: The .DS_Store (Desktop Service Store) is a hidden file containing attributes of its enclosing folder, such as the icon size display. The __MACOSX folder is created during the zip process and contains metadata about the compressed files.




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签