In the following code, I upload the .txt file to the ftp server. When the file is uploaded, I delete it on my local machine.
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()
print 'File uploaded, now deleting...'
except all_errors as e:
print 'error'
print str(e)
os.unlink(filepath)
The code works, but sometimes (every ~ 10th download) I get this error message:
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'
So the file cannot be deleted because "it has not been released" or something else? I also tried to disable the file this way:
while True:
try:
os.unlink(filepath)
break
except all_errors as e:
print 'Cannot delete the File. Will try it again...'
print str(e)
But with "try except block" I also get the same error "The process cannot access the file because it is being used by another process"! The script did not even try to print the exception:
'Cannot delete the File. Will try it again...'
and just stopped (like above).
How can I get os.unlink to do my job correctly? Thank!
source
share