问题
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 printedsep='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 issys.stdoutflush: Optional. A Boolean, specifying if the output is flushed (True) or buffered (False). Default isFalse
回答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