用python读取文件中的单个行

时间:2016-03-10 02:00:07

标签: python

这怎么回事?看来我每次都这样做是对的。我尝试将readline部分更改为read,但这不起作用。

这是我的代码:

f = open("pg1062.txt","r").read()
print f.readline(1)
print f.readline(2)
print f.readline(3)

这是我得到的错误:

 print f.readline(1)
AttributeError: 'str' object has no attribute 'readline'

3 个答案:

答案 0 :(得分:1)

你的问题就在这一行

f = open("pg1062.txt","r").read()

只需删除.read()即可解决您的问题。你的最终代码应该是这样的。

f = open("pg1062.txt","r")
print f.readline()
print f.readline()
print f.readline()

如果您想打印文本文件中的所有行,请参阅下面的代码

f = open("pg1062.txt","r")
for line in f:
    print line

答案 1 :(得分:1)

这使用循环打印您的线条。

f = open("pg1062.txt", 'r')
while True:
    line = f.readline()
    if line == "":
        break
    print(line)

如果您只想打印特定数量的行,请执行以下操作:

f = open("pg1062.txt", 'r')
count = 1
while count < 4:
    line = f.readline()
    if line == "":
        break
    print(line)
    count += 1

答案 2 :(得分:0)

这肯定是重复的。无论如何,Python 2.4以上的任何内容都应使用with块。

with open("pg1062.txt", "r") as fin:
    for line in fin:
        print(line)

如果你碰巧想要他们在列表中:

with open("pg1062.txt", "r") as fin:
    lines = [line for line in fin] # keeps newlines at the end
    lines = [line.rstrip() for line in fin] # deletes the newlines

或更多或更少等同

with open("pg1062.txt", "r") as fin:
    lines = fin.readlines() # keeps newlines at the end
    lines = fin.read().splitlines() # deletes the newlines