使用以下代码,我将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 because block“,我也得到了同样的错误”该进程无法访问该文件,因为它正被另一个进程使用“!该脚本甚至没有尝试打印异常:
'Cannot delete the File. Will try it again...'然后就停下来了(就像上面的)。
我怎样才能让os.unlink做好他的工作呢?谢谢!
发布于 2010-01-17 23:33:30
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发布于 2010-01-18 00:51:08
您需要在try/except的except分支上关闭(文件和ftp会话),否则文件将继续被“旧的”超时ftp会话引用(因此,您需要在while循环内打开文件,而不是在它的外部打开文件) --关闭else分支上的文件和ftp会话是不够的,因为这不会消除失败的、超时的尝试(如果有的话)带来的引用。
发布于 2010-01-18 10:19:11
我的代码仍然有问题,它并不像我需要的那样健壮。例如,登录过程可能会失败。也许user+pass错了,也许服务器很忙。
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 definedhttps://stackoverflow.com/questions/2081289
复制相似问题