You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中每隔5秒读取CSV数据?有无替代time.sleep()的方法?

问题解答

能不能用time.sleep()实现?

可以,但你的代码逻辑和语法都有问题——你现在是一次性把整个CSV加载到内存,之后只是循环遍历内存里的数据并间隔等待,这不是“每隔5秒读取一次数据”,而是读一次文件后每隔5秒取内存里的一行。

如果你的需求是遍历已加载的行并间隔处理,那time.sleep()完全可行,但要先修正语法错误:

import time
import numpy as np

data_signal = np.loadtxt(pname + fname,
                      delimiter=';',
                      skiprows=1)
# 补全for循环的括号和冒号
for i in range(len(data_signal)):
      data = data_signal[i]
      # 这里添加处理data的逻辑
      time.sleep(5)

如果你的需求是每隔5秒从磁盘重新读取CSV(比如文件会被外部程序实时更新),那得把读取操作放进循环:

import time
import numpy as np

while True:
    # 每次循环都重新读取文件
    data_signal = np.loadtxt(pname + fname,
                          delimiter=';',
                          skiprows=1)
    # 处理最新读取的数据
    # ...
    time.sleep(5)

其他可行实现方式

  • 用sched模块:适合复杂定时场景,支持任务优先级和延迟调度
import sched
import time
import numpy as np

def read_csv(sc):
    data_signal = np.loadtxt(pname + fname, delimiter=';', skiprows=1)
    # 处理数据
    # ...
    # 5秒后再次调度任务
    sc.enter(5, 1, read_csv, (sc,))

s = sched.scheduler(time.time, time.sleep)
s.enter(0, 1, read_csv, (s,))
s.run()
  • 用threading.Timer:通过线程实现定时,适合不想阻塞主线程的场景
import threading
import time
import numpy as np

def read_csv():
    data_signal = np.loadtxt(pname + fname, delimiter=';', skiprows=1)
    # 处理数据
    # ...
    # 5秒后再次执行任务
    threading.Timer(5, read_csv).start()

# 启动第一次读取
read_csv()

# 保持主线程存活
while True:
    time.sleep(1)
  • 跟踪文件新增内容(比如CSV是实时追加的日志):不用重复读整个文件,只取新增行
import time

def follow_csv(file_path):
    with open(file_path, 'r') as f:
        # 跳到文件末尾
        f.seek(0, 2)
        while True:
            line = f.readline()
            if not line:
                time.sleep(5)
                continue
            # 解析单行CSV数据(注意处理分隔符)
            # ...

follow_csv(pname + fname)

内容的提问来源于stack exchange,提问作者nana

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 20:35:25