Connecting Tech Pros Worldwide Forums | Help | Site Map

read in from file

Newbie
 
Join Date: Oct 2008
Posts: 14
#1: Oct 5 '08
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.

Expand|Select|Wrap|Line Numbers
  1.  
  2. li = []
  3.  
  4.  
  5. for i in range(0,9): #<- these must be the correct range.    
  6.     temp = raw_input("")
  7.     li.append(temp)
  8.  
  9.  

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

Expand|Select|Wrap|Line Numbers
  1.  
  2. if(temp==\0):
  3.       break
  4.  
  5.  
and similar but not having to much luck. Thanks for reading!

JS

bvdet's Avatar
Moderator
 
Join Date: Oct 2006
Location: Nashville, TN
Posts: 1,563
#2: Oct 5 '08

re: read in from file


Iteration on a file object will terminate when the EOF character is reached.
Expand|Select|Wrap|Line Numbers
  1. f = open('file.txt')
  2. for i, line in enumerate(f):
  3.     print 'Line number %d' % i
  4.     ## do more stuff
  5.  
  6. f.close()
  7.  
Newbie
 
Join Date: Oct 2008
Posts: 14
#3: Oct 5 '08

re: read in from file


Thanks bvdet .

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

Expand|Select|Wrap|Line Numbers
  1.  
  2. def readWords():
  3.     while 1:
  4.         line = raw_input()
  5.         if line != "":
  6.             listOfWords.append(line);
  7.         else:
  8.             break
  9. #End read words method
  10.  
  11.  
Newbie
 
Join Date: Oct 2008
Posts: 14
#4: Oct 7 '08

re: read in from file


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

Regardless, this code works:

Expand|Select|Wrap|Line Numbers
  1.  
  2. # reads words from the input file
  3. def readWords():
  4.     jake = sys.stdin
  5.     listOfWords= jake.readlines()
  6.     listOfWords = [i[:-1] for i in listOfWords]
  7.     return listOfWords
  8.  
  9.  
  10.  
Reply