Python-如何访问zip文件中的文件夹并写入其中

时间:2018-01-29 14:50:18

标签: python

您好我试图从z.jar访问文件。 文件结构类似于z.jar \ org(文件夹)。 这里Org是一个文件夹,我试图访问z.jar中的org文件夹并尝试编写一些东西。任何人都可以帮助我吗?

import zipfile
def show_jar_classes(jar_file):
    """prints out .class files from jar_file"""
    zf = zipfile.ZipFile(jar_file, 'w')
    try:
        #Code to write inside org folder in inside z.jar
        zf.write('India.txt')
    finally:
        zf.close()

jar_file='D:/pyt/z.jar'
show_jar_classes(jar_file)

2 个答案:

答案 0 :(得分:1)

调整您的代码。使用writestr对我有用:

import zipfile, os

def show_jar_classes(jar_file):
    """prints out .class files from jar_file"""
    zf = zipfile.ZipFile(jar_file, 'w')
    try:
        #Code to write inside org folder in inside z.jar
        filename = 'Org\\India.txt' # name of the file
        fcontent = b'India is a great country' # content
        zf.writestr(filename,fcontent,zipfile.ZIP_DEFLATED)

    finally:
        zf.close()

jar_file = 'D:/pyt/z.jar'
show_jar_classes(jar_file)

答案 1 :(得分:0)

更换' w'模式与' a'模式帮助我解决了我遇到的问题:

import zipfile, os

def show_jar_classes(jar_file):

    zf = zipfile.ZipFile(jar_file, 'a')
    try:
        #Code to write inside org folder in inside z.jar
        filename = 'org\\India.txt' # name of the file
        fcontent = 'India is a great country' # content
        zf.writestr(filename,fcontent,zipfile.ZIP_DEFLATED)

    finally:
        zf.close()

jar_file = 'D:/python/z.jar'

show_jar_classes(jar_file)