简体   繁体   中英

reading lines from file in python via for loop

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 ?

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.

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

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.

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM