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


当前回答

如果你想读取file。txt

line1 helloworld

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

其他回答

这应该做到:

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

如果你想读取file。txt

line1 helloworld

import linecache
# read first line
print(linecache.getline('file.txt'), 1)
>helloworld
fline=open("myfile").readline().rstrip()
first_line = next(open(filename))
infile = open('filename.txt', 'r')
firstLine = infile.readline()