使用以下代码,我将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 正常工作?
谢谢!
all_errors
到底是什么?如果其中没有WindowsError
(或其超类),那么异常就不会被捕获。 - balphaftplib
或os.unlink
没有任何关系。这只是使用了all_errors
。 - SilentGhostwhile True
循环? - SilentGhost