LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   PYTHON - basic question (https://www.linuxquestions.org/questions/programming-9/python-basic-question-4175439861/)

DBabo 12-03-2012 04:14 PM

PYTHON - basic question
 
Hello,
why the following code is not working as i expect it to :
Code:


#!/usr/bin/python

from_file ="file.txt"
in_file = open(from_file)

str = in_file.read()

print "Here should be the output from the file - ", in_file.read()
print "Here should be the output from the STR- ", str
in_file.close()


The output is :
Here should be the output from the file -
Here should be the output from the STR- BLAH

in other words print "". in_file.read() doesn't seem to work. I wonder why?

jlinkels 12-03-2012 05:07 PM

you have to import sys, not just argv from sys.
Code:

import sys
jlinkels

DBabo 12-03-2012 05:11 PM

Quote:

Originally Posted by jlinkels (Post 4842066)
you have to import sys, not just argv from sys.
Code:

import sys
jlinkels

it doesn't look like it's using it. I took the import completely out ( and updated the code above). Still getting the same behavior.

dugan 12-03-2012 05:41 PM

I'm not sure what you expect to see. You read one line from the file and assign it to STR. You then read the next line from the file and print it out. The output shows that the first line read from the file (and assigned to STR) is "BlAH" and the next line read from the file is empty.

DBabo 12-03-2012 08:44 PM

Quote:

Originally Posted by dugan (Post 4842081)
I'm not sure what you expect to see. You read one line from the file and assign it to STR. You then read the next line from the file and print it out. The output shows that the first line read from the file (and assigned to STR) is "BlAH" and the next line read from the file is empty.

well well i wanted to see the content of the file...
But i think I understand what you meant - i read the file into variable str and the pointer (or whatever it's called in python) is @ the end of the file. So when i read the file again - i get 0 bytes.
ekhh silly me.

Thank you for the tip!
AZ

dugan 12-04-2012 11:30 AM

Quote:

Originally Posted by DBabo (Post 4842139)
well well i wanted to see the content of the file... But i think I understand what you meant - i read the file into variable str and the pointer (or whatever it's called in python) is @ the end of the file. So when i read the file again - i get 0 bytes.

You are correct. The read() method reads the entire file, not one line. Silly me too.

Ref: http://docs.python.org/2/library/std...l#file-objects


All times are GMT -5. The time now is 05:05 PM.