richard kappler
2015-09-09 13:05:23 UTC
Would either or both of these work, if both, which is the better or more
Pythonic way to do it, and why?
#######################
import whatIsNeeded
writefile = open("writefile", 'a')
with open(readfile, 'r') as f:
for line in f:
if keyword in line:
do stuff
f1.write(line)
else:
f1.write(line)
writefile.close()
######################
import whatIsNeeded
with open(readfile, 'r') as f:
for line in f:
try:
if keyword in line:
do stuff
except:
do nothing
with open(writefile, 'a') as f1:
f1.write(line)
######################
or something else altogether?
I'm thinking the first way is better as it only opens the files once
whereas it seems to me the second script would open and close the writefile
once per iteration, and the do nothing in the except seems just wrong to
me. Is my thinking on target here?
regards, Richard
Pythonic way to do it, and why?
#######################
import whatIsNeeded
writefile = open("writefile", 'a')
with open(readfile, 'r') as f:
for line in f:
if keyword in line:
do stuff
f1.write(line)
else:
f1.write(line)
writefile.close()
######################
import whatIsNeeded
with open(readfile, 'r') as f:
for line in f:
try:
if keyword in line:
do stuff
except:
do nothing
with open(writefile, 'a') as f1:
f1.write(line)
######################
or something else altogether?
I'm thinking the first way is better as it only opens the files once
whereas it seems to me the second script would open and close the writefile
once per iteration, and the do nothing in the except seems just wrong to
me. Is my thinking on target here?
regards, Richard
--
All internal models of the world are approximate. ~ Sebastian Thrun
_______________________________________________
Tutor maillist - ***@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
All internal models of the world are approximate. ~ Sebastian Thrun
_______________________________________________
Tutor maillist - ***@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor