python - 将坐标写入 .txt 文件以供将来在程序中使用
问题描述
我创建的代码在单击后显示我单击的坐标,我的问题是将这个东西附加到名为 coord.txt 的 txt 文件中,代码是:
from pynput import mouse
def on_click(x, y, button, pressed):
c=open("coord.txt", "w+")
if button == mouse.Button.left:
print(x, y)
c.write(x)
c.write(y)
return False
c.flush()
listener = mouse.Listener(on_click=on_click)
listener.start()
listener.join()
错误是:
TypeError: write() argument must be str, not int
但我尝试没有任何帮助。将来我想将此 def 与我在 pyqt5 gui 中的所有工具按钮配对,如下所示: https ://github.com/spokom/mycodes/tree/master
解决方案
您需要将x
and转换y
为字符串才能编写它们。
此外,您应该用分隔符将它们分开,否则当您尝试读回它们时,您只会得到一个数字。
def on_click(x, y, button, pressed):
with open("coord.txt", "w") as c:
if button == mouse.Button.left:
print(x, y)
c.write(str(x) + "\n")
c.write(str(y) + "\n")
return False
无需+
在打开模式下使用修饰符。您只是在写入文件,而不是从中读取。
推荐阅读
- javascript - 从 html 之类的字符串中提取文本值
- reactjs - Packery 在 React 组件中可拖动
- vps - Virtualmin 邮件未收到。主目录中的两个邮件文件夹
- javascript - 对象在 VueJS 组件中为空
- python - Python OpenCV 测量
- node.js - escodegen.generate 抛出错误:未知节点类型:未定义
- python - 如何将数据添加到现有的 Pandas Dataframe 列
- python - JSON文件与Python中的主键合并
- c# - 使用 EF 的单元测试数据库
- excel - 如何识别电子邮件是否在 Excel 的日期范围内重复?