How to read CSV file one row at the time in a range and some delay in between - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: How to read CSV file one row at the time in a range and some delay in between (/thread-31017.html) |
How to read CSV file one row at the time in a range and some delay in between - greenpine - Nov-18-2020 Hello, I am new to Python, I want to read a CSV file, but have some problems, hopefully, get some help, I have a one-column data on CSV file since it is just one column data I am not sure if it does make any difference using a text file or CSV file, anyhow I want to get each row of data from a range ( e.g. row 5 to row 14) one by one with some delay in between, but with the code, I have there some problems.
import csv csvfile = open('my_file.csv','r') csvFileArray = [] for row in csv.reader(csvfile): csvFileArray.append(row) print(csvFileArray[5:11]) time.sleep(5)I want to insert this row of data in another function, but for the purpose of testing this code I use print function. I am grateful for your help to make this work. Here is the output data: and here is how the data is in CSV file:
RE: How to read CSV file one row at the time in a range and some delay in between - perfringo - Nov-18-2020 Something like this? import time with open('one_row_at_time.csv', 'r') as f: for i, line in enumerate(f, start=1): if i in range(5, 15): # rows 5-14 print(line) # use line.rstrip() to handle newline if needed time.sleep(2)One should break out of loop if needed lines are processed, but it should be trivial to add/refactor code. There is also itertools module with suitable functions. As you probably know, slice will not raise any error if indices are out-of-bounds. So you can't be sure of number of lines (if any) printed/returned: >>> 'abc'[2:20] 'c' >>> 'abc'[5:20] '' RE: How to read CSV file one row at the time in a range and some delay in between - greenpine - Nov-20-2020 Thanks for the code, I tried it and it works. |