Question about file objects...
pruebauno at latinmail.com
Wed Dec 2 15:27:28 CET 2009
On Dec 2, 9:14 am, J <dreadpiratej... at gmail.com> wrote:
> Something that came up in class...
> when you are pulling data from a file using f.next(), the file is read
> one line at a time.
> What was explained to us is that Python iterates the file based on a
> carriage return as the delimiter.
> But what if you have a file that has one line of text, but that one
> line has 16,000 items that are comma delimited?
> Is there a way to read the file, one item at a time, delimited by
> commas WITHOUT having to read all 16,000 items from that one line,
> then split them out into a list or dictionary??
> Ogden Nash - "The trouble with a kitten is that when it grows up,
> it's always a cat." -http://www.brainyquote.com/quotes/authors/o/ogden_nash.html
File iteration is a convenience since it is the most common case. If
everything is on one line, you will have to handle record separators
manually by using the .read(<number_of_bytes>) method on the file
object and searching for the comma. If everything fits in memory the
straightforward way would be to read the whole file with .read() and
use .split(",") on the returned string. That should give you a nice
list of everything.
More information about the Python-list