I often have to open files solely to read in the text and do some analysis on the text as in the following example.
with open('foo/bar.txt') as f:
text = f.read()
good_stuff = analyze(text)
My question is, does the good_stuff line need to be indented? As far as I understand the with block exists to automate build up and tear down of some process. If this is all it does then once I have the text variable, I'm all good and no longer need to be in the with block, correct?
If I have lots of surrounding code, this can lead to large indentation which can be rather annoying. I've tried not indenting and it seems to work, but I've never seen anyone write
with open('foo/bar.txt') as f:
text = f.read()
good_stuff = analyze(text)
so I'm curious if there is some reason or standard this is done, or maybe I haven't noticed some side effect this causes.
The second approach is actually better. You should exit the with block as soon as you are done with the file. There is no need to keep the file open after you read it.
In this approach:
with open('foo/bar.txt') as f:
text = f.read()
good_stuff = analyze(text)
You opened the file, read the whole content into a variable called text, you have closed the file and then you analyzed the text.
This is OK, but what if you have get a very big file? In that case I don't think you can go with this approach
with open('foo/bar.txt') as f:
for line in f:
good_stuff = analyze(line)
So this is how I suggest to read your file if you have a big file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With