首页 > 解决方案 > 编写 csv 时循环错误或语法不正确?

问题描述

我正在尝试使用 pyautogui 记录鼠标位置的输出或 X 和 Y 坐标,并将它们写入 csv 文件。每当我运行我的代码时,它会在单独的列中打印出 X 和 Y,这很好,但是在 X 下方的左上角,它显示“True”,然后在 Y 列下方的一行中,它也显示“True”。我真的不明白为什么会这样。

import pyautogui, sys
import numpy as np
import csv

try:
    while True:
        x, y = pyautogui.position()
        positionStr = 'X: ' + str(x).rjust(4) + ' Y: ' + str(y).rjust(4)
        print(positionStr)
except KeyboardInterrupt:
    print('\n')

while True:
    with open('Mousemovement.csv', mode = 'w') as csv_file:
        fieldnames = ['X', 'Y']
        writer = csv.DictWriter(csv_file, fieldnames = fieldnames)
        writer.writeheader()
        writer.writerow({'X': x in pyautogui.position()})
        writer.writerow({'Y': y in pyautogui.position()})

标签: pythonpyautogui

解决方案


x in pyautogui.position()

使用 Pythonin运算符。这是测试membership- 基本上,确实x存在于pyautogui.position(). 这将返回一个boolean值(TrueFalse)。然后将该值写入您的 CSV 文件。

此外,您writerow每次循环调用两次,这就是您的 Y 值出现在 X 下方的原因。

最后,您将多次打开和写入 CSV 文件。您应该只打开一次,写入标题,然后进入循环写入值。

你只需要像这样重写你的代码:

with open('Mousemovement.csv', mode = 'w') as csv_file:
    fieldnames = ['X', 'Y']
    writer = csv.DictWriter(csv_file, fieldnames = fieldnames)
    writer.writeheader()
    while True:
        x, y = pyautogui.position() # Get the position into x and y
        writer.writerow({'X': x, 'Y': y}) # Pass a single dictionary, so one row is printed

推荐阅读