Help | Site Map
Connecting Tech Pros Worldwide
Reply
 
LinkBack Thread Tools
  #1  
Old October 5th, 2008, 03:44 PM
Newbie
 
Join Date: Oct 2008
Posts: 8
Default 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.

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
Reply
  #2  
Old October 5th, 2008, 04:16 PM
bvdet's Avatar
Expert
 
Join Date: Oct 2006
Location: Nashville, TN
Posts: 1,219
Default

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

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

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
Reply

Bookmarks

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are Off
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On

What is Bytes?

We are a network of experts and professionals in IT and software development that help one another with answers to tough questions and share insights. Get the best answers to your questions from over network members.
Post your question now . . .
It's fast and it's free

Popular Articles