read in from file

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • sixtyfootersdude
    New Member
    • Oct 2008
    • 14

    read in from file

    Hi all,

    trying to write a program that will read a file in like:

    python myprog < inputFile

    the program needs to store each line a an entry in a list.

    Code:
    li = []
    
    
    for i in range(0,9): #<- these must be the correct range.    
    	temp = raw_input("")
    	li.append(temp)

    This code works but you have to hard code how many lines there will be (see comment). I need my program to terminate at the EOF. I have looked around for a couple hours but havent had enormous luck finding anything.

    Tryed entering in

    Code:
    if(temp==\0):
          break
    and similar but not having to much luck. Thanks for reading!

    JS
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    Iteration on a file object will terminate when the EOF character is reached.[code=Python]f = open('file.txt' )
    for i, line in enumerate(f):
    print 'Line number %d' % i
    ## do more stuff

    f.close()
    [/code]

    Comment

    • sixtyfootersdude
      New Member
      • Oct 2008
      • 14

      #3
      Thanks bvdet .

      For anyone with a similar problem as me this is the way I ended up doing it:

      Code:
      def readWords():
      	while 1:
      		line = raw_input()
      		if line != "":
      			listOfWords.append(line);
      		else:
      			break
      #End read words method

      Comment

      • sixtyfootersdude
        New Member
        • Oct 2008
        • 14

        #4
        Ooops. The previous code does not detect EOF (well it does sometimes, just not not always...)

        Regardless, this code works:

        Code:
        # reads words from the input file
        def readWords():
        	jake = sys.stdin
        	listOfWords= jake.readlines()
        	listOfWords = [i[:-1] for i in listOfWords]
        	return listOfWords

        Comment

        Working...