2016-09-21 93 views
0

我有一個jar文件,我有一個代表Jar文件內部位置的路徑。使用python zipfile命令替換/添加類文件到jar文件中的子文件夾

使用此位置我需要替換jar文件中的類文件(在某些情況下添加一個類文件)。我有另一個文件夾內存在的jar文件存在的類文件(這個類文件我必須移動到Jar) 。我想實現上述目標

代碼:

Jar 
    |----META-INF 
    |----com.XYZ 
    |----Mystuff 
      |--testclass.class 

實際輸出我需要的是 -

Jar 
    |----META-INF 
    |----com.XYZ 
      |--ABC 
       |-testclass.class 

import zipfile 
import os 

zf = zipfile.ZipFile(os.path.normpath('D:\mystuff\test.jar'),mode='a') 
try: 
    print('adding testclass.class') 
    zf.write(os.path.normpath('D:\mystuff\testclass.class')) 
finally: 
    print('closing') 
    zf.close() 

,當我看到罐子下文提到的格式上面的代碼執行後

在python中如何使用zipfile.write命令或任何其他方式來實現這一點?

我沒有在寫命令中找到任何參數,我可以在Jar/Zip文件中提供目標文件位置。

ZipFile.write(文件名,arcname =無,compress_type =無)

回答

0

指定arcname改變在存檔的文件的名稱。

import zipfile 
import os 

zf = zipfile.ZipFile(os.path.normpath(r'D:\mystuff\test.jar'),mode='a') 
try: 
    print('adding testclass.class') 
    zf.write(os.path.normpath(r'D:\mystuff\testclass.class'),arcname="com.XYZ/ABC/testclass.class") 
finally: 
    print('closing') 
    zf.close() 

注:我懷疑test.jar是你的真實姓名罐子,因爲你沒有保護你的字符串中的特殊字符,並打開了jar文件會一直'D:\mystuff\<TAB>est.jar'(當然,這是行不通的:))

編輯:如果您要添加新的文件,但刪除了舊的,你要做的是不同的:你不能從一個壓縮文件中刪除,你必須重建一個又一個(由Delete file from zipfile with the ZipFile Module啓發)

import zipfile 
import os 

infile = os.path.normpath(r'D:\mystuff\test.jar') 
outfile = os.path.normpath(r'D:\mystuff\test_new.jar') 

zin = zipfile.ZipFile(infile,mode='r') 
zout = zipfile.ZipFile(outfile,mode='w') 
for item in zin.infolist(): 
    if os.path.basename(item.filename)=="testclass.class": 
     pass # skip item 
    else: 
     # write the item to the new archive 
     buffer = zin.read(item.filename) 
     zout.writestr(item, buffer) 

print('adding testclass.class') 
zout.write(os.path.normpath(r'D:\mystuff\testclass.class'),arcname="com.XYZ/ABC/testclass.class") 

zout.close() 
zin.close() 

os.remove(infile) 
os.rename(outfile,infile) 
+0

但舊文件不會被替換。有沒有什麼辦法從罐子裏提供的文件中提取文件的路徑 – Manjunath

+0

是的,請參閱我的編輯。 –

相關問題