简体   繁体   中英

How can i write to a File after a Certain Key is Pressed and then get to a new Line

I am very new to python but i dont know what i can do to fix my problem. This underneath is my code but but the file does not collect all the things it should to write there. I would appreciate any help.

Thank you. Edit:

Thank you its fixed now but i have another problem that the things arent appearing very fast and its kinda laggy. Is there anything that would help?(I already tried to set down the time.sleep part.

import time

from pynput.mouse import Button, Controller

from pynput.keyboard import *
import mouse




def press_on(key):

    print('Press ON: {}'.format(key))

    if key == key.right:
        mouse.move(1028, 350, absolute=True, duration=0.02)
        time.sleep(0.3)
        mouse.click("left")
        time.sleep(0.3)
        with open('Get Position.txt', 'w') as f:
            f.write('RIGHT')
            f.write('\n')
            f.close()


    if key == key.down:
        mouse.move(959, 350, absolute=True, duration=0.02)
        time.sleep(0.3)
        mouse.click("left")
        time.sleep(0.3)

        with open('Get Position.txt', 'w') as f:
            f.write('MID')
            f.write('\n')
            f.close()



def press_off(key):
    print('Press OFF: {}'.format(key))
    if key == Key.up:
        return False

with Listener(on_press = press_on, on_release = press_off) as listener:
    listener.join()

Open the file in append mode - 'a' and not 'w'.

with open('file.txt', 'a') as f:
  f.write('line\n')

with open('file.txt', 'a') as f:
  f.write('this line will be appended\n')

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