С помощью следующего кода я загружаю файл 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)
Но при попытке "за исключением блока" я также получаю ту же ошибку "Процесс не может получить доступ к файлу, поскольку он используется другим процессом"! Скрипт даже не пытался напечатать исключение:
'Cannot delete the File. Will try it again...'
и просто остановился (как выше).
Как я могу заставить os.unlink правильно выполнять свою работу?
Спасибо!