我有我需要添加到tar歸檔文件的目錄。的目錄結構是:使用Python將多個文件從多個目錄添加到獨特的.tar.gz文件中
..\root\path\dirname\somefiles.txt
和含有somefiles.ext。tar.gz的文件應該被存入.. \根\路徑\爲:
..\root\path\dirname.tar.gz
,我目前已經是該代碼:
import os, tarfile
for root, dirs, files in os.walk('.'):
for dir in dirs:
tar = tarfile.open(dir + '.tar.gz', 'w:gz')
for file in files:
tar.add(os.path.join(root, file))
tar.close()
然而,這從..\root\path\
而不是..\root\path\dirname\
拉文件。我該如何編寫這個文件來將文件從每個目錄中提取出來,並將它們添加到同名目錄的存檔中?
編輯
隨着使用@ mVChr的代碼,我能得到我所需要的。我添加了arcname=f
以刪除檔案中的目錄;我不知道爲什麼我之前沒有實現:
import os, tarfile
for root, dirs, _ in os.walk('.'):
for d in dirs:
with tarfile.open(d + '.tar.gz', 'w:gz') as tar:
for _, _, files in os.walk(os.path.join(root, d)):
for f in files:
tar.add(os.path.join(root, d, f), arcname=f)
我明白你的觀點是指變量名稱。這也會在存檔中創建一個目錄:.. \ root \ path \ dirname.tar.gz \ dirname \ somefiles.ext另外你也省去了tar.close()。 – user2998182
我沒有遺漏'tar.close()',這是我關於使用'with'的意思,它是爲你做的。 http://docs.python.org/2/reference/compound_stmts.html#the-with-statement和'inspect.getsource(tarfile.TarFile .__ exit __)' – mVChr
啊,我明白了。我的錯。是否可以截斷流程中的目錄層次結構?我只想要這些文件,沒有文件夾... – user2998182