Python:从FTP读完后删除文件

时间:2011-10-10 17:46:18

标签: python url gzip

我的python脚本从FTP打开一个gzip文件并读取它。每次运行脚本.gz时,文件都会下载到我的Harddisk(Sites / htdocs文件夹,因为它是一个python cgi)。我不想将文件下载到我的硬盘上,或者在执行脚本后删除文件。

这是我的剧本的快照:

u = 'http://hapmap.ncbi.nlm.nih.gov/downloads/frequencies/2010-05_phaseIII/'

filename1 = 'allele_freqs_chr' + chromosomes[i] + '_' + populations[0] + '_phase3.3_nr.b36_fwd.txt.gz'
url = u + filename1
try:
    site = urllib.urlretrieve(url,filename1)
except IOError:
    print >> sys.stderr,'Error opening URL.\n'
try: 
    f1 = gzip.open(filename1, 'rb')
except IOError:
    print >> sys.stderr, 'Error opening file1.\n'
    sys.exit(1) 

line=f1.readline()
# ...

感谢您的建议。

2 个答案:

答案 0 :(得分:3)

os.unlink(filename1)应该有效。另外,在finally:块中使用try:来关闭文件描述符,如下所示:

import os
u = 'http://hapmap.ncbi.nlm.nih.gov/downloads/frequencies/2010-05_phaseIII/'
filename1 = 'allele_freqs_chr' + chromosomes[i] + '_' + populations[0] + '_phase3.3_nr.b36_fwd.txt.gz'
url = u + filename1
try:
    site = urllib.urlretrieve(url,filename1)
except IOError:
    print >> sys.stderr,'Error opening URL.\n'
try: 
    f1 = gzip.open(filename1, 'rb')
except IOError:
    print >> sys.stderr, 'Error opening file1.\n'
    sys.exit(1)
else:
    line = f1.readline()
    # ....
finally:
    try:
        f1.close()
    except:
        pass

os.unlink(filename1)

答案 1 :(得分:0)

您可以使用urllib.urlopen代替urllib.urlretrieve

fd = urllib.urlopen(url)
s_data = fd.read()                    # These 2 lines are unfortunately
s_stream = StringIO.StringIO(s_data)  # needed in Python < 3.2
f1 = gzip.GzipFile(fileobj=s_stream)

另请参阅:http://www.enricozini.org/2011/cazzeggio/python-gzip/(关于为什么必须使用StringIO)