在Python中结合使用ftplib和os.unlink

3 投票
3 回答
953 浏览
提问于 2025-04-15 18:07

下面的代码可以把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”这个结构时,我还是收到了同样的错误:“该进程无法访问文件,因为它正在被另一个进程使用”!脚本甚至没有尝试打印出这个异常:

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

然后就直接停止了(像上面那样)。

我该怎么做才能让os.unlink正常工作呢?谢谢!

3 个回答

0

你需要在 except 这部分关闭文件和FTP连接,否则文件会一直被“旧的”超时FTP会话引用(所以你需要在 while 循环里面打开文件,而不是在外面)——仅仅在 else 部分关闭文件和FTP连接是不够的,因为这样无法清除来自失败的、超时的尝试的引用(如果有的话)。

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
0

我在代码上还是遇到了一些问题,它没有我需要的那么稳定。比如说,登录的过程可能会失败。可能是用户名和密码不对,也可能是服务器忙。

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

撰写回答