Python:从 FTP 读取完后删除文件
我的 python 脚本从 FTP 打开一个 gzip 文件并读取它。每次我运行脚本时,.gz
文件都会下载到我的硬盘上(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()
# ...
我感谢您的建议。
My python script opens a gzip file from FTP and reads it. Every time I run the script .gz
files are downloaded to my Harddisk (Sites/htdocs folder as its a python cgi). I dont want to download the files to my harddisk or else delete the files after execution of script.
Here is snapshot of my script:
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()
# ...
I appreciate your suggestions.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
os.unlink(filename1) 应该可以工作。另外,在
try:
块中使用finally:
来关闭文件描述符,如下所示:os.unlink(filename1)
should work. Also, usefinally:
in yourtry:
block to close the file descriptor like so:您可以使用
urllib.urlopen
代替urllib.urlretrieve
另请参阅:http://www.enricozini.org/2011/cazzeggio/python-gzip/ (关于为什么必须使用 StringIO)
You can use
urllib.urlopen
instead ofurllib.urlretrieve
See also: http://www.enricozini.org/2011/cazzeggio/python-gzip/ (On why you have to use StringIO)