So I have a csv data and I want my program to read the data every 5 seconds. So between the first data and the second data there is a reading distance of 5 seconds.
Can I use time.sleep()
or is there another way to do it?
data_signal = np.loadtxt(pname fname,
delimiter=';',
skiprows=1)
for i in range(len(data_signal)
data = data_signal[i]
time.sleep(5)
CodePudding user response:
Consider that time.sleep()
is blocking further script execution. If you want things to run on timer and go on running your code consider to use a callback_timer
class which you can adapt to your needs. Below code which demonstrates the principle of the callback timer:
from threading import Timer
class callback_timer():
def __init__(self, data_signal=None, timespan=None):
if not isinstance(data_signal, str) or not ( isinstance(timespan, int) or isinstance(timespan, float)):
raise Exception("callback_timer(): bad or not specified parameter")
self.counter = len(data_signal)
self.data_signal = data_signal
self.timespan = timespan
self.timer = Timer(timespan, self.get_data, args=["noArgs"])
self.timer.start()
print( 'callback_timer() START' )
def get_data(self, noArgs):
curr_signal = self.data_signal[len(self.data_signal) - self.counter]
print('callback_timer() countdown =', self.counter, "curr_signal=", curr_signal)
... # some code for processing curr_signal ...
self.counter -= 1
if self.counter < 1:
print( 'callback_timer() STOP' )
return True
self.timer = Timer(self.timespan, self.get_data, args=["noArgs"])
self.timer.start()
if __name__ == '__main__':
data_signal = '0-1-ax' # ... some data_signal'
print ('Got to main(), timer message in 3 seconds.')
cb = callback_timer(data_signal, 3) # doesn't block execution of next code line
print ('main() after creation of test_timer() object')
giving following output:
Got to main(), timer message in 3 seconds.
callback_timer() START
main() after creation of test_timer() object
callback_timer() countdown = 6 curr_signal= 0
callback_timer() countdown = 5 curr_signal= -
callback_timer() countdown = 4 curr_signal= 1
callback_timer() countdown = 3 curr_signal= -
callback_timer() countdown = 2 curr_signal= a
callback_timer() countdown = 1 curr_signal= x
callback_timer() STOP
See also Python Timer Callback Method providing code stripped down to demonstration of the callback timer principle only.
CodePudding user response:
for z in range(1, len(YourFileOpen)):
with open(f'{z}.csv') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=';')
line_count = 0
for row in csv_reader:
value1 = row[0]
value2 = row[2]
after this use print and (import time) after print insert your sleep:
print(f"{value1}\n{value2}\n")
time.sleep(5)