Python Loop Won't Iterate On Second Pass
When I run the following in the Python IDLE Shell: f = open(r'H:\Test\test.csv', 'rb') for line in f: print line #this works fine however, when I run the following for a s
Solution 1:
This does not work because you've already seeked to the end of the file the first time. You need to rewind (using .seek(0)) or re-open your file.
Some other pointers:
- Python has a very good
csvmodule. Do not attempt to implement CSV parsing yourself unless doing so as an educational exercise. - You probably want to open your file in
'rU'mode, not'rb'.'rU'is universal newline mode, which will deal with source files coming from platforms with different line endings for you. - Use
withwhen working with file objects, since it will cleanup the handles for you even in the case of errors. Ex:
.
withopen(r"H:\Test\test.csv", "rU") as f:
for line in f:
...
Solution 2:
Because you've gone all the way through the CSV file, and the iterator is exhausted. You'll need to re-open it before the second loop.
Post a Comment for "Python Loop Won't Iterate On Second Pass"