Putting "source.txt" to variable as this:
source = open('/home/user/tmp/python/source.txt','r')
with source as f:
[...]
script doesn't run, why? The below script runs:
#!/usr/bin/python
with open('/home/user/tmp/python/source.txt','r') as f:
for line in f:
if 'www.yahoo.it' in line:
print (line)
The first case does run, but it simply opens a file and binds the file object to variable source. It does nothing further with it. If you want to read the content of the file you need to iterate over its lines (as in your second example), or call source.read() to read the data.
source = open('/home/user/tmp/python/source.txt','r')
for line in source:
if 'www.yahoo.it' in line:
print(line)
source.close()
The second example from your question is better because it guarantees that the file will be closed upon exit from the context handler (the with statement).
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