On 07/31/2013 04:12 PM, Mike McTernan wrote:
I am having problems with the readline command in Python 2.7.

I have a text file that has 12 lines of text, each line represents a
response to a variable called star_sign that is collected via
raw_input.

However, instead of printing the line 5 it prints the first 5 letters on line 1.

Here is the program:

from sys import argv

script, zodiac = argv

prediction = open(zodiac, "r")

prompt = "> "

def welcome():
     print "Welcome to your daily horoscope"
     horoscope()

def horoscope():
     print "I can predict your future"
     print "What is your starsign?"
     star_sign = raw_input(prompt)

     if "Leo" in star_sign:
         print prediction.readline(5)

That 5 limits the number of bytes that readline() will read to 5. I doubt if that's what you wanted.


     else:
         print "You gonna die"

welcome()

I suggest instead that you replace the prediction line with

infile = open(zodiac, "r")
predictions = infile.readlines()
infile.close()

And the print line with
                 print predictions[5]

Notice that predictions is now a list of strings, each representing one line of the file. They also have newlines, so you may want to strip() them, but that's a minor issue.


--
DaveA

_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to