2011-11-16 51 views
21

我想使用Python來gzip文件。我正在嘗試使用subprocss.check_call(),但它與錯誤'OSError:[Errno 2]沒有這樣的文件或目錄'一直失敗。我在這裏嘗試的是否有問題?有沒有比使用subprocess.check_call更好的方式來gzip文件?在Python中使用gzip文件

from subprocess import check_call 

def gZipFile(fullFilePath) 
    check_call('gzip ' + fullFilePath) 

謝謝!!

+11

爲什麼不能http://docs.python.org/library/gzip.html? – Ski

+0

相關:從目錄'/ dir/path'創建一個gzipped tarball'archive.tar.gz',你可以使用'shutil.make_archive'('archive','gztar','/ dir/path')' – jfs

回答

13

試試這個:

check_call(['gzip', fullFilePath]) 

根據您正在使用這些文件的數據做什麼,Skirmantas的鏈接http://docs.python.org/library/gzip.html也可能會有所幫助。請注意頁面底部附近的例子。如果您不需要訪問數據,或者您的Python代碼中沒有數據,那麼執行gzip可能是最簡單的方法,因此您不必使用Python處理數據。

+0

好吧,idk如果「乾淨」是正確的話,但它肯定是最快的方式,並且需要最少的代碼在你身邊。 –

46

有一個模塊gzip。使用方法:

Jace Browning's answer

import gzip 
f_in = open('/home/joe/file.txt') 
f_out = gzip.open('/home/joe/file.txt.gz', 'wb') 
f_out.writelines(f_in) 
f_out.close() 
f_in.close() 

編輯:

import gzip 
content = "Lots of content here" 
f = gzip.open('/home/joe/file.txt.gz', 'wb') 
f.write(content) 
f.close() 

如何GZIP壓縮現有的文件示例:

如何創建壓縮GZIP文件例Python中的= with> = 2.7顯然更簡潔易讀,所以我的第二個片段會(和sh烏爾德)看起來像:

import gzip 
with open('/home/joe/file.txt') as f_in, gzip.open('/home/joe/file.txt.gz', 'wb') as f_out: 
    f_out.writelines(f_in) 
+0

第二個版本是否會用gzip命令替換原始文件?它似乎沒有。 –

+1

@Benoît:由於輸出文件的名稱與正在讀取的名稱不同,因此很明顯它不會這樣做。這樣做需要將壓縮數據臨時存儲在其他地方,直到原始文件中的所有數據都被壓縮。 – martineau

+0

使用gzip,輸出文件名與輸入文件名不同。並且它在創建輸出文件之後仍然會刪除輸入文件。我只是問是否python gzip模塊做了同樣的事情。 –

5

使用gzip模塊:

import gzip 
import os 

in_file = "somefile.data" 
in_data = open(in_file, "rb").read() 
out_gz = "foo.gz" 
gzf = gzip.open(out_gz, "wb") 
gzf.write(in_data) 
gzf.close() 

# If you want to delete the original file after the gzip is done: 
os.unlink(in_file) 

你的錯誤:OSError: [Errno 2] No such file or directory'是告訴你該文件fullFilePath不存在。如果您仍然需要走這條路線,請確保您的系統上存在該文件,並且您使用的絕對路徑不是相對路徑。

+0

感謝大家的快速repoonses.Everyone這裏是建議gzip.I曾試過,以及它是一種更好的方式?我不使用的原因是,它保留原來的文件,所以我結束了兩個版本 - 常規和gzip文件。我正在訪問文件的數據,雖然。@ retracile,你的修復工作,感謝噸。我仍然想知道如果我應該使用子進程或gzip。 – Rinks

+1

@Rinks最簡單的方法是:當gzip完成時,調用'os.unlink(original_File_Name)'來刪除你製作gzip的原始文件。查看我的編輯。 – chown

+1

@Rinks:_我之所以不使用它,是因爲它將原始文件保留爲is_ - 那麼爲什麼不在以後刪除文件呢? – Xaerxess

28

在Python 2.7格式:

import gzip 

with open("path/to/file", 'rb') as orig_file: 
    with gzip.open("path/to/file.gz", 'wb') as zipped_file: 
     zipped_file.writelines(orig_file) 

甚至更​​短(測試蟒2.7。6)

with open('path/to/file') as src, gzip.open('path/to/file.gz', 'wb') as dst:   
    dst.writelines(src) 
3

在此文檔實際上是出奇直截了當的如何讀取壓縮文件

實施例:

import gzip 
f = gzip.open('file.txt.gz', 'rb') 
file_content = f.read() 
f.close() 

如何創建壓縮GZIP文件例

import gzip 
content = "Lots of content here" 
f = gzip.open('file.txt.gz', 'wb') 
f.write(content) 
f.close() 

如何GZIP壓縮現有文件的示例:

import gzip 
f_in = open('file.txt', 'rb') 
f_out = gzip.open('file.txt.gz', 'wb') 
f_out.writelines(f_in) 
f_out.close() 
f_in.close() 

https://docs.python.org/2/library/gzip.html

這就是全部的文檔。 。 。