Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

None value returned

Tags:

python

The code below is used in a function:

def print_query(x):
    h = open('/home/rv/data.txt', 'r')
    read = h.readlines()
    for line in read:
        return line

When the value "line" is retunred it should print but instead i get the value "None"

like image 216
Liam Avatar asked Mar 20 '26 19:03

Liam


2 Answers

Try this:

with open('/home/rv/data.txt','r') as fh:
    for line in fh:
        print line

If you're on Python 2.5 you might need a from __future__ import with_statement on top.

Also: why do you return the line when you want to print it?

like image 134
ChristopheD Avatar answered Mar 23 '26 09:03

ChristopheD


You are not checking if the "read" variable actually contains any lines - if it does not, then the function will fall through the for loop and return None.

Using the for loop is also silly - why would you read all lines, and only return the first one, especially in a for loop? What happens when the file can't be opened?

like image 23
Yann Ramin Avatar answered Mar 23 '26 09:03

Yann Ramin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!