Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

putting opening file to variable [closed]

Tags:

python

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)
like image 918
Marco Rimoldi Avatar asked May 07 '26 02:05

Marco Rimoldi


1 Answers

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).

like image 130
mhawke Avatar answered May 08 '26 15:05

mhawke