write mouse position to .txt file [duplicate]

♀尐吖头ヾ 提交于 2021-02-11 07:33:33

问题


My little project is to write coordinates to file and my code look like this:

import pyautogui
import time

c = open("coord.txt", "w")
while True:
        x, y = pyautogui.position()
        positionStr = str(x).rjust(4) + str(y).rjust(4)
        print(positionStr)
        c.write(positionStr)
        time.sleep(1)

It not work becouse it show in terminal the coordinates but file coord.txt is still empty


回答1:


You are just missing to flush inside the loop. The write method doesn't necessarily write the data to disk. You have to call the flush method to ensure this happens.

import pyautogui
import time

c = open("coord.txt", "w")
while True:
    x, y = pyautogui.position()
    positionStr = str(x).rjust(4) + str(y).rjust(4)
    print(positionStr)
    c.write(positionStr + '\n')
    c.flush()
    time.sleep(1)

Is better to replace c = open("coord.txt", "a") with with open("coord.txt", "w") as c: so when the loop end the file automatically close otherwise you need to call close.

import pyautogui
import time

with open("coord.txt", "w") as c:
    while True:
        x, y = pyautogui.position()
        positionStr = str(x).rjust(4) + str(y).rjust(4)
        print(positionStr)
        c.write(positionStr + '\n')
        c.flush()
        time.sleep(1)

You can also use the print() function to write to the file:

import pyautogui
import time

with open("coord.txt", "w") as c:
    while True:
        x, y = pyautogui.position()
        positionStr = str(x).rjust(4) + str(y).rjust(4)
        
        print(positionStr)
        print(positionStr, file=c, flush=True)

        time.sleep(1)

This is because the print() is defined as print(object(s), sep=separator, end=end, file=file, flush=flush) where:

  • object(s): Any object, and as many as you like. Will be converted to string before printed
  • sep='separator': Optional. Specify how to separate the objects, if there is more than one. Default is ' '
  • end='end': Optional. Specify what to print at the end. Default is '\n' (line feed)
  • file: Optional. An object with a write method. Default is sys.stdout
  • flush: Optional. A Boolean, specifying if the output is flushed (True) or buffered (False). Default is False



回答2:


you need to change mode from w to a so that it can append to a file.

import pyautogui
import time

with open("coord.txt", "a") as writer: #This is better so that you dont have to worry about closing the file
    while True:
        x, y = pyautogui.position()
        positionStr = str(x).rjust(4) + str(y).rjust(4)
        print(positionStr)
        writer.write(positionStr+"\n")
        time.sleep(1)



回答3:


Remember to do c.close() or c.flush() after you write the file.

Maybe duplicate of This question



来源:https://stackoverflow.com/questions/64046117/write-mouse-position-to-txt-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!