gpt4 book ai didi

python - ftplib 结合 python 中的 os.unlink

转载 作者:行者123 更新时间:2023-11-28 19:28:26 24 4
gpt4 key购买 nike

使用以下代码,我将 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 正常工作?谢谢!

最佳答案

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

关于python - ftplib 结合 python 中的 os.unlink,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2081289/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com