python - 编写 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()})
解决方案
x in pyautogui.position()
使用 Pythonin
运算符。这是测试membership
- 基本上,确实x
存在于pyautogui.position()
. 这将返回一个boolean
值(True
或False
)。然后将该值写入您的 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
推荐阅读
- html - HTML/CSS 格式化列宽与换行列
- java - 即使 xml 中存在值,为什么我在 java 中从 xml 获取 null?
- dart - 如何使用带有角飞镖的花生包在github页面上部署项目?
- c# - SOAP 中的 UDP 和 WCF 有什么区别?
- django - 如何使用序列化程序处理图像
- java - 对于 Kotlin 中的高阶函数,为什么 lambdas 显示在其他函数参数之外?
- javascript - 在Javascript中将函数参数传递给then
- javascript - 使用 Array.sort() 获取单个比较函数以对 ASC 和 DESC 进行排序?
- jenkins - 为什么 SonarScanner 忽略 sonar.sources 值(您必须定义以下强制属性)?
- scala - 无法使用内置 toLocalIterator() 将 Spark 数据集转换为迭代器