Python - 在 .csv 文件中查找特定行并将其替换为新行

发布于 2025-01-12 05:26:58 字数 1035 浏览 2 评论 0原文

希望这里有人能够在我陷入困境时帮助我。

我在三个不同城市的家里有三个 Raspberry Pi。他们每小时检查家里的温度和湿度,然后连接到我本地的 Raspberry Pi,并将温度和湿度以及日期和时间记录在 .csv 文件中。生成的文件显示为(每行中的前两个值始终相同):

Philadelphia, kitchen, 67.3, 40.2, 03/05/2022, 15:30:33
Miami, kitchen, 75.3, 50.2, 03/05/2022, 15:45:37
Dayton, basement, 63.1, 45.3, 03/05/2022, 15:22:30
Dayton, den, 63.7, 44.3, 03/05/2022, 15:22:30

我想要完成的是找到一个特定行并在上传新值时替换它。例如,我需要将第 3 行更改为:

Dayton, basement, 64.8, 45.5, 03/05/2022, 16:22:35

我已使用 SSH 以及公钥和私钥成功将值写入文件:

temp = ("Dayton, " + "basement, " + temp + ", " + humidity + ", " + date + ", " + time)
def put_file(machinename, port, username):
  ssh = paramiko.SSHClient()
  ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()
  ssh.connect(machinename, port, username=username)
  sftp = ssh.open_sftp()
  f = sftp.open('/home/PiSix/MagicMirror/modules/MMM-MyTemp/Data/Temps.csv', 'w')
  f.write(temp)
  f.close()

put_file('mydomain.ddns.net', port, 'PiSix')

有人知道我正在寻找的答案吗?

Hopefully someone here will be able to help me as I am stuck.

I have three Raspberry Pi's in homes in three different cities. Every hour they check the temperature and humidity in the home and then connect to my local Raspberry Pi and record the temperature and humidity in a .csv file along with the date and time. The resulting file appears as (the first two values in each line will always be the same):

Philadelphia, kitchen, 67.3, 40.2, 03/05/2022, 15:30:33
Miami, kitchen, 75.3, 50.2, 03/05/2022, 15:45:37
Dayton, basement, 63.1, 45.3, 03/05/2022, 15:22:30
Dayton, den, 63.7, 44.3, 03/05/2022, 15:22:30

What I am trying to accomplish is to find one particular line and replace it when the new values are uploaded. For example, I need to change line 3 to:

Dayton, basement, 64.8, 45.5, 03/05/2022, 16:22:35

I am successfully writing the values to the file using SSH with public and private keys:

temp = ("Dayton, " + "basement, " + temp + ", " + humidity + ", " + date + ", " + time)
def put_file(machinename, port, username):
  ssh = paramiko.SSHClient()
  ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()
  ssh.connect(machinename, port, username=username)
  sftp = ssh.open_sftp()
  f = sftp.open('/home/PiSix/MagicMirror/modules/MMM-MyTemp/Data/Temps.csv', 'w')
  f.write(temp)
  f.close()

put_file('mydomain.ddns.net', port, 'PiSix')

Anyone have the answer that I am seeking?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文