繁体   English   中英

Python:如何在不知道文件实际存在多长时间的情况下从文件中读取一大块文本?

[英]Python: How do you read a chunk of text from a file without knowing how long the file actually is?

我想做的是基本上我有这个文件的数据是单独的行,除了最后一篇是传记,可能会延伸到很多行。 传记可以是任意数量的行,我所知道的是它从第5行开始。 现在我需要的是一种从第五行到文件末尾检索传记的方法,但我不知道如何做到这一点。 提前致谢。

这是我试过的:

from tkinter import *
import os

class App:

    charprefix = "character_"
    charsuffix = ".iacharacter"
    chardir = "data/characters/"


    def __init__(self, master):
        self.master = master
        frame = Frame(master)
        frame.pack()

        # character box
        Label(frame, text = "Characters Editor").grid(row = 0, column = 0, rowspan = 1, columnspan = 2)
        self.charbox = Listbox(frame)
        for chars in []:
            self.charbox.insert(END, chars)
        self.charbox.grid(row = 1, column = 0, rowspan = 5)
        charadd = Button(frame, text = "   Add   ", command = self.addchar).grid(row = 1, column = 1)
        charremove = Button(frame, text = "Remove", command = self.removechar).grid(row = 2, column = 1)
        charedit = Button(frame, text = "    Edit    ", command = self.editchar).grid(row = 3, column = 1)

        for index in self.charbox.curselection():
            charfilelocale = self.charbox.get(int(index))
            charfile = open(app.chardir + app.charprefix + app.charfilelocale, 'r+')
            charinfo = str.splitlines(0)

如果您只想将整个传记放在一个字符串中,您可以这样做:

with open('biography.txt') as f:
    for i in range(4): # Read the first four lines
        f.readline()
    s = ''
    for line in f:
        s += line

for line in f ”迭代f iter(f)返回一个生成函数,生成f.readline()直到达到文件末尾。

另一种表达你的问题的方法是“如何丢弃我读过的文件的前四行?” 一步一步地回答这个问题:

filename = "/a/text/file"
input_file = open(filename)

其中open()的默认模式是'r'因此您不必指定它。

contents = input_file.readlines()
input_file.close()

其中readlines()返回一个gulp中输入文件中包含的所有行的列表。 你无论如何都要读它,所以让我们用一个方法调用来做。 而且,当然是close()因为你是一个整洁的程序员。 现在,您可以使用列表切片来获取所需的部件:

biography = contents[4:]

实际上并没有丢掉前四行,它只是将前四个分配给了传记。 为了使这更加惯用,给出了:

with open(filename) as input_file:
    biography = input_file.readlines()[4:]

with上下文管理器很有用,但在准备好后查找它。 在这里它保存了close()但它比那更强大。

添加以回应评论

就像是

with open(filename) as input_file:
    contents = input_file.readlines()
person = contents[0]
birth_year = contents[1]
...
biography = contents[4:]

但我觉得你在打字的时候觉得有点不对劲。

f = open('workfile','w')

for f in line:print line,

This is the first line of the file.
Second line of the file

Python不要求您事先知道文件有多大或包含多少行。 它使用迭代器并从文件中获取行并延迟返回行。 在这里找到一些优秀的文档: http//docs.python.org/2/tutorial/inputoutput.html

暂无
暂无

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

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