假設有路徑/home/somebody/test1/test2/test3/
該路徑下有3個檔案,a.txt, b.txt, c.txt
在目錄/home/somebody下有如下**,希望打包a.txt, b.txt, c.txt三個檔案
#coding=utf8
import
json
import
gzip
import
msgpack
import
tarfile
import
osdef
test_tar(fname_out, dir_in):
tar = tarfile.open(fname_out, '
w:gz')
for root, dir, files in
os.walk(dir_in):
for file in
files:
fullpath =os.joinpath(root, file)
tar.add(fullpath
) tar.close()
os.chdir(cur_path)
if__name__ == "
__main__":
test_tar(
"test_tar.gz
", "test1/test2/test3
")
解壓test_tar.gz結果
test1/test2/test3/a.txttest1/test2/test3/b.txt
test1/test2/test3/c.txt
問題出現了,解壓後保留了原有的路徑!!可這不是我想要的啊,我只想要三個檔案啊!
經測試,壓縮檔案的路徑跟tarfile.add()中的路徑完全一致,所以需要在add時把當當前目錄轉換到/home/somebody/test1/test2/test3/,等打包後在把當前目錄還原即可
#coding=utf8
import
json
import
gzip
import
msgpack
import
urllib
import
urllib2
import
tarfile
import
osdef
test_tar(fname_out, dir_in):cur_path=os.getcwd()full_fname_out =os.path.join(cur_path, fname_out)
full_path_in =os.path.join(cur_path, dir_in)os.chdir(full_path_in)tar = tarfile.open(full_fname_out, '
w:gz')
for root, dir, files in
os.walk(full_path_in):
for file in
files:
fullpath =file
tar.add(fullpath, recursive=false)
tar.close()os.chdir(cur_path)if
__name__ == "
__main__":
test_tar(
"test_tar.gz
", "test1/test2/test3
")
**如上所示,關鍵部分加粗顯示了。這樣解壓結果中就沒有複雜的目錄結構了
a.txtb.txt
c.txt
Python tarfile路徑問題
假設在目錄test1 test2下有兩個檔案a.txt和b.txt test1 test2 a.txt b.txt test3 test4現在需要將其壓縮至test1 test3目錄下 很容易得到 def tar files file name,from path,to path tar file ...
開發路,學習路
經過1年多的coding,做了幾個專案以後,終究在自己覺得最看不起的地方跌倒了,以前在學習的時候竟然認為程式設計思想嘛 理論嘛,那些都是無所謂的東西,應該更加注重coding的實踐 因為自己的夢想就是成為乙個coding牛人 然後在幾次回頭修正 擴充套件自己以往做過的專案的時候,我才發現,許久的co...
人生的路很遠,一路小心
1 別跟墮落的人比墮落。墮落起來非常容易,可是墮落後再想回到不墮落,難。不要給自己頹廢的機會。2 不要以為躲在學校裡就可以忽略外面世界的殘酷現實。競爭越來越激烈 人越來越多,職位卻越來越少。學校裡固然溫柔,但不能因而醉生夢死。否則,乙個舒服的打坐之後,一睜眼,頭頂已經踩上了一片人,想起身,卻發現已經...