tags:

views:

225

answers:

7

After reading in a file how would tell python to read the first line only?

+2  A: 

This should do it:

f = open('myfile.txt')
first = f.readline()
Jarret Hardie
+6  A: 
infile = open('filename.txt', 'r')
firstLine = infile.readline()
Jaelebi
+10  A: 
with open('myfile.txt', 'r') as f:
  first_line = f.readline()

Some notes, thanks to commenters:

  1. The with statement automatically closes the file again when the block ends.
  2. The with statement only works in python 2.5 and up, and in python 2.5 you need to use from __future__ import with_statement
  3. In Python 3 you should specify the file encoding for the file you open. Read more...
Tor Valamo
+1 for with statement.
Mark Byers
+0.9 for with statement, rounded up, assuming you forgot to back it up with a link to why the with statement is a good idea, so I include it here: http://effbot.org/zone/python-with-statement.htm
Joel
You might want note that this only works with python 2.5 and later. You also might want to mention that in python 3 you should pass an encoding argument to the open function.
Zach Bialecki
A: 

I'm going to go ahead and spice this up a little bit:

with open('myfile.txt','r') as f:
    line = f.readline()
Bryan Ross
A: 
fline=open("myfile").readline().rstrip()
+4  A: 

Lots of other answers here, but to answer precisely the question you asked:

>>> f = open('myfile.txt')
>>> data = f.read()
>>> # I'm assuming you had the above before asking the question
>>> first_line = data.split('\n', 1)[0]

In other words, if you've already read in the file (as you said), and have a big block of data in memory, then to get the first line from it efficiently, do a split() on the newline character, once only, and take the first element from the resulting list.

Note that this does not include the \n character at the end of the line, but I'm assuming you don't want it anyway (and a single-line file may not even have one). Also note that although it's pretty short and quick, it does make a copy of the data, so for a really large blob of memory you may not consider it "efficient". As always, it depends...

Peter Hansen
If this is a big file, f.read() will try to load the entire file into memory which would not be a good idea. An alternative would be to read one character at a time until a newline or EOF is encountered
TP
Actually, all the other answers are better alternatives than that. Normally reading a file with readline() and friends would load entire blocks at a time, maybe 32K give or take, and search through that to find the next newline. Much faster and more efficient. My answer would be useful only if he's *already* loading the entire thing, in which case we can assume he's okay with having it all in memory.
Peter Hansen
A: 

To go back to the beginning of an open file, do this:

my_file.seek(0)
dangph
Also a reasonable way to answer a poorly worded question. :)
Peter Hansen