ftplib与python中的os.unlink结合使用

时间:2010-01-17 14:28:33

标签: python exception

使用以下代码我将file.txt上传到ftp服务器。文件上传后,我将在本地计算机上删除它。

import os
from ftplib import FTP

HOST = 'host.com'
FTP_NAME = 'username'
FTP_PASS = 'password'
filepath = 'C:\file.txt'
while True:
    try:
        ftp = FTP(HOST)
        ftp.login(FTP_NAME, FTP_PASS)
        file = open(filepath, 'r')
        ftp.storlines('STOR file.txt', file)
        ftp.quit()
        file.close() # from this point on the file should not be in use anymore
        print 'File uploaded, now deleting...'
    except all_errors as e: #EDIT: Got exception here 'timed out'
        print 'error'       #      then the upload restarted.
        print str(e)

os.unlink(filepath) # now delete the file

代码有效,但有时(每次上传第10次)我收到此错误消息:

Traceback (most recent call last):
in os.unlink(filepath)
WindowsError: [Error 32] The process cannot access the file
because it is being usedby another process: 'C:\file.txt'

因此,该文件无法删除,因为“它尚未发布”或其他内容?我还尝试以这种方式取消链接文件:

while True: # try to delete the file until it is deleted...
    try:
        os.unlink(filepath)
        break
    except all_errors as e:
        print 'Cannot delete the File. Will try it again...'
        print str(e)

但是使用“try except block”我也得到了同样的错误“进程无法访问该文件,因为它正被另一个进程使用”!该脚本甚至没有尝试打印异常:

'Cannot delete the File. Will try it again...'

刚刚停止(如上所述)。

如何让os.unlink正常工作? 谢谢!

3 个答案:

答案 0 :(得分:0)

import os
from ftplib import FTP

HOST = 'host.com'
FTP_NAME = 'username'
FTP_PASS = 'password'
filepath = 'C:\file.txt'
file = open(filepath, 'r')
while True:
    try:
        ftp = FTP(HOST)
        ftp.login(FTP_NAME, FTP_PASS)        
        ftp.storlines('STOR file.txt', file)
    except all_errors as e: #EDIT: Got exception here 'timed out'
        print 'error'       #      then the upload restarted.
        print str(e)
    else:
        ftp.quit()
        file.close() # from this point on the file should not be in use anymore
        print 'File uploaded, now deleting...'   
        os.unlink(filepath) # now delete the file
        break

答案 1 :(得分:0)

您需要在try / except的except分支上关闭(文件和ftp会话),否则该文件将被“旧”超时ftp会话引用(因此您需要在while循环内打开文件,而不是在它之外 - 仅仅关闭else腿上的文件和ftp会话是不够的,因为它没有摆脱失败的引用,超时尝试(如果有的话)。

答案 2 :(得分:0)

我仍然遇到代码问题,它不像我需要的那样强大。 例如,登录过程可能会失败。也许用户+传递错误,也许sesrver很忙。

try:
    ftp = FTP(HOST) # HOST is a valid host address
    ftp.login('test', 'test111111') # WRONG user + pass to test code robustness
    ftp.quit()
except all_errors as e:
    ftp.quit()
    print str(e)

问题是except块中的ftp.quit()。 Python返回以下错误(非异常):

Traceback (most recent call last):
    File "test.py", line 9, in <module>
        ftp.quit()
NameError: name 'ftp' is not defined