0

I wrote this code

for i in range(40):
    f=open('file.txt','r')
    if i%2==1:
        f.readlines()[i]

But it didnt print anything on console.

Whereas if I write it this way, it does:-

for i in range(40):
    f=open('fil.txt','r')
    if i%2==1:
        p=f.readlines()[i]
        print p

Why is it so. f.readlines() works on console, but why it doesnt work inside a loop ?

0

5 Answers 5

2

Why should the first one print anything on the console? You don't call print anywhere. The second one calls print, so obviously it prints.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Daniel. What i meant to ask was , why is that simply firing "f.readlines()" doesnt work inside a loop, whilst it works on terminal/console. Why do I need to write "print f.readlines()" in order to print inside a loop?
0

In your first bit of code you don't have a print statement. Fix it to be like so:

for i in range(40):
    f=open('file.txt','r')
    if i%2==1:
        print(f.readlines()[i])

Comments

0

You don't need to open the file each time, and you don't need to read the contents of the file each time (and you're not printing at all in your first bit of code):

from itertools import islice

with open('file') as fin:
    for line in islice(fin, 1, 40, 2):
        print line

The above code will print the odd numbered lines from the file.

2 Comments

Is there any other way of doing what you just did. I mean yeah ,its inefficient to keep opening a file during the entire iteration. So is there any other simpler method of opening a file only once for the entire iteration
Yeah - this just opens it once... - not sure what you mean?
0

f.readlines() works on console

At the Python interpreter, all values are implicitly printed. This means, when you type the name, its string representation is automatically printed:

>>> a = 'hello'
>>> a
'hello'

However, when you are writing a script, you need to use print:

a = 'hello'
print(a)

Comments

0

What you're referring to as the console is probably the interactive interpreter. In the interactive interpreter, results of expressions are automatically shown, making it usable much like a calculator; it performs a read-eval-print loop. When running a prepared program, there is no assumption of the print step (nor, technically, the read step), so you must request it if that is what you want done.

A quite separate issue is how you read the entire file 40 times, splitting it into lines each time, when you only intend to print 20 lines. I would probably rewrite the loop like so:

f=open('fil.txt','r')
for i in range(40):
    p=f.readline()
    if i%2==1:
        print p

The reason I don't use f.e. for line in file('filename'): is that I don't intend to process the whole file; placing the range in the for line shows the limits at a glance.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.