如何使用Python只获取文件的第一行作为字符串?


当前回答

first_line = next(open(filename))

其他回答

如果你想读取file。txt

line1 helloworld

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

要返回打开文件的开头,然后返回第一行,请执行以下操作:

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

这应该做到:

f = open('myfile.txt')
first = f.readline()
infile = open('filename.txt', 'r')
firstLine = infile.readline()
first_line = next(open(filename))