Connecting Tech Pros Worldwide Help | Site Map

read in from file

  #1  
Old October 5th, 2008, 03:44 PM
Newbie
 
Join Date: Oct 2008
Posts: 12
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
  #2  
Old October 5th, 2008, 04:16 PM
bvdet's Avatar
Moderator
 
Join Date: Oct 2006
Location: Nashville, TN
Posts: 1,545

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.  
  #3  
Old October 5th, 2008, 05:01 PM
Newbie
 
Join Date: Oct 2008
Posts: 12

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.  
  #4  
Old October 7th, 2008, 10:51 AM
Newbie
 
Join Date: Oct 2008
Posts: 12

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


Similar Threads
Thread Thread Starter Forum Replies Last Post
From file to char* array OziRus answers 8 December 26th, 2006 11:35 PM
problem with reading from file mitek777@o2.pl answers 12 April 14th, 2006 05:35 PM
How to save and read very big Array Value to/from file in VB.NET? oncelovecoffee answers 4 November 20th, 2005 11:35 PM
reading float point from file Affan Syed answers 6 July 22nd, 2005 11:27 PM