【发布时间】:2010-01-17 14:28:33
【问题描述】:
使用以下代码,我将 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 正常工作? 谢谢!
【问题讨论】:
-
您确定该文件没有在文本编辑器中打开吗?还是已打开而文本编辑器仍未关闭?
-
对不起,我忘记了我在 ftplib 中使用了一个 while 循环!不知道它是否相关,但是在存储之后我得到了一个异常“超时”,然后 ftpupload 重新启动。之后 os.unlink 不起作用(正在使用的进程...)
-
all_errors到底是什么?如果WindowsError(也不是它的超类)不存在,这就是异常不会被捕获的原因。 -
我想我应该将 all_errors 替换为 WindowsError? :> 我认为由于 ftpupload 中的异常,os.unlink 无法完成他的工作。但是,对于“除了 WindowsError as e:”,“while 删除循环”应该可以工作
-
好吧,那和
ftplib或os.unlink无关。这只是all_errors的用法。