Python Forum

Full Version: read a text file, find all integers, append to list
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2
What I mean is, certain, "Python objects", for instance the result of csv.reader() can only be used 1 time. I just wonder why.

Example:

import csv
myfile = '/home/pedro/myPython/csv/time.csv'
csv_reader = csv.reader(myfile, delimiter=',')
for row in csv_reader:
    print(row)
Output:
['time', ' comment'] ['2022-04-25 7:06 AM', ' bla '] ['2022-04-25 7:07 AM', ' blabla'] ['2022-04-25 7:08 AM', ' ha'] ['2022-04-25 7:09 AM', ' haha']
But, if you try to use csv_reader again, it's gone!

for row in csv_reader:
    print(row)
You get nothing, csv_reader is "burned" and unavailable. You would have to read it in again.

That was the same with your code in this thread. I didn't put *Nset in the text file, so the whole of file was searched.

After that file was unavailable for the second loop.

I just wonder why that is.

For practical purposes, I read csv_reader into a list, which remains available for as many uses as I want.
(Aug-11-2022, 12:27 AM)Pedroski55 Wrote: [ -> ]But, if you try to use csv_reader again, it's gone!

That's the way file objects work. Unless you do special handling, the read pointer moves forward in file as you consume it and stops at the end. If you keep reading, it doesn't magically loop back to the front of the file. You're expected to either reopen the file or seek to the front of the file if you want to read it again.

import csv

f = open("time.csv")
r = csv.reader(f)
for line in r:
    print(line)

# lets re-read the file.
f.seek(0)
for line in r:
    print(line)
But reading a file (I/O) is expensive. Better to avoid repeating it. Either try to do everything in one pass, or as you're already doing (if the file is small enough), read it into memory and operate on the copy in memory.
Aha, thanks, I have heard of f.seek() but never had cause to use it.

I'll read some more about it!
Pages: 1 2