开发者

Read only the first line of a file?

开发者 https://www.devze.com 2022-12-14 12:51 出处:网络
How would you get only the first line of a file as a string with Pytho开发者_StackOverflow社区n?Use the .readline() method:

How would you get only the first line of a file as a string with Pytho开发者_StackOverflow社区n?


Use the .readline() method:

with open('myfile.txt') as f:
    first_line = f.readline()

Note that unless it is the only line in the file, the string returned from f.readline() will contain a trailing newline. You may wish to use

with open('myfile.txt') as f:
    first_line = f.readline().strip('\n')

instead, to remove the newline.


infile = open('filename.txt', 'r')
firstLine = infile.readline()


fline=open("myfile").readline().rstrip()


To go back to the beginning of an open file and then return the first line, do this:

my_file.seek(0)
first_line = my_file.readline()


This should do it:

f = open('myfile.txt')
first = f.readline()


first_line = next(open(filename))


Lots of other answers here, but to answer precisely the question you asked (before @MarkAmery went and edited the original question and changed the meaning):

>>> 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...


If you want to read file.txt

line1 helloworld

import linecache
# read first line
print(linecache.getline('file.txt'), 1)
>helloworld
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号