简体   繁体   English

使用python读取文件中的单个行

[英]reading individual line in a file with python

How is this wrong? 这怎么了 It seems like I am doing this right but every time. 好像我每次都做对了。 I have tried changing the readline part to read but that didn't work. 我尝试将readline部分更改为read但这没有用。

Here is my code: 这是我的代码:

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

Here is the error I get: 这是我得到的错误:

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

Your problem is at this line 你的问题在这条线上

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

just remove .read() and your problem will be fixed. 只需删除.read()解决您的问题。 Your final code should look like. 您的最终代码应如下所示。

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

And if you want to print all lines from text file, see code below 如果要打印文本文件中的所有行,请参见下面的代码

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

This uses a loop to print your lines. 这使用循环来打印行。

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

If you want to only print a specific number of lines, then do something like this: 如果您只想打印特定数量的行,请执行以下操作:

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

This is certainly a duplicate. 这肯定是重复的。 At any rate, anything above Python 2.4 should use a with block. 无论如何,Python 2.4以上的版本都应使用with块。

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

If you happen to want them in a list: 如果您碰巧希望它们出现在列表中:

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

or more or less equivalently 或多或少等效

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM