Python只打印第一行文本文件

时间:2017-06-26 09:01:45

标签: python

我有一个带有几行的文本文件并想要打印它们,但它只打印第一行。如果我使用循环(参见下面的代码),它会垂直打印第一行..

file = open('file.txt', 'r')
data = file.read()
file.close()
for line in data:
     print (line)

5 个答案:

答案 0 :(得分:4)

file = open('file.txt', 'r')
data = file.readlines()
for line in data:
     print (line)
file.close()

答案 1 :(得分:4)

尝试使用with自动关闭文件并使代码更具可读性/ pythonic:

with open('file.txt', 'r') as f:
    for line in f.readlines():
        print (line)

答案 2 :(得分:2)

使用with语句来阅读文本文件通常是一个好主意。

with open('file.txt', 'r') as file:
  data = file.read()

要仅读取第一行,请使用readline()为此(使用readlines(),其他答案建议效率不高):

with open('file.txt', 'r') as file:
  first_line = file.readline()

答案 3 :(得分:2)

for line in open('file.txt', 'r'):
    print(line)

答案 4 :(得分:-1)

<强> file.txt的

1 foo buzz bizz foo buzz bizz foo buzz bizz foo buzz bizz foo buzz bizz
2 foo foo foo foo foo foo foo foo foo foo bizz bizz bizz bizz foo foo
3 foo foo foo foo foo foo foo foo foo foo bizz bizz bizz bizz foo foo
4 foo buzz bizz foo buzz bizz foo buzz bizz foo buzz bizz foo buzz bizz
5 foo foo foo foo foo foo foo foo foo foo bizz bizz bizz bizz foo foo
6 foo buzz bizz foo buzz bizz foo buzz bizz foo buzz bizz foo buzz bizz

执行:

def print_first_lines(filename, n):
    with open(filename, 'r') as desc:
        for _ in range(n):
            print(desc.readline().strip())

print_first_lines('file.txt', 1)

输出:

1 foo buzz bizz foo buzz bizz foo buzz bizz foo buzz bizz foo buzz bizz