简体   繁体   English

python readline()返回多行

[英]python readline() returns multiple lines

I think I have created a problem for myself.... 我想我为自己制造了一个问题。

I have two functions and a global file descriptor(file object) 我有两个函数和一个全局文件描述符(文件对象)

def fileController():
    global fd
    fName = ui.fileEdit.text()
    if ui.lineByLine.isChecked:
        ui.fileControl.setText('Next Line')
        ui.fileControl.clicked.connect(nextLine)
    fd = open(fName, 'r')

def nextLine():
    global fd
    lineText = fd.readline()
    print lineText

def main():
    app = QtGui.QApplication(sys.argv)
    global ui
    ui = uiClass()

    ui.fileControl.clicked.connect(fileController)
    ui.lineByLine.stateChanged.connect(lineByLineChange)

    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

when nextLine() is called, it returns the first line. 当调用nextLine()时,它返回第一行。
if it is called again it returns the first line and the second line. 如果再次调用它将返回第一行和第二行。
if it is called yet again it returns the first line and the second line and the third line. 如果再次调用它,则返回第一行,第二行和第三行。 etc. etc. 等等等

could the file descriptor being a global variable cause this? 文件描述符是全局变量会导致这种情况吗?

complete un-redacted code can be found here 完整的未编辑代码可以在这里找到

all help is appreciated! 感谢所有帮助!

EDIT: included more of the code for context 编辑:包括更多的上下文代码
EDIT2: added link to github project file EDIT2:添加了指向github项目文件的链接

SOLVED: problem was that: 解决:问题是:

ui.fileControl.clicked.connect(nextLine)

does not disconnect the previous signal. 不会断开先前的信号。 so every time file Control() was clicked a "signal and slot" was added so that newLine() was called multiple times. 因此,每次单击Control()文件时,都会添加“信号和插槽”,以便多次调用newLine()。 And as fileController was still being called the file was being reopened. 并且由于fileController仍被调用,因此文件被重新打开。 So I saw the behaviour above. 所以我看到了上面的行为。 Thanks for all the advice! 感谢所有的建议!

You could write a class to encapsulate such operations: 您可以编写一个类来封装此类操作:

class MyFile(object):
    def __init__(self, filename=''):
        self.fp    = open(filename, 'rb')
        self.state = 0 # record the times of 'nextline()' called
        self.total = self.lines_num()

    def lines_num(self):
        """Calculate the total lines of the file"""
        count   = 0
        abuffer = bytearray(2048)
        while self.fp.readinto(abuffer) > 0:
            count += abuffer.count('\n')
        self.fp.seek(0)

        return count

    def nextline(self):
        """Returning -1 means that you have reached the end of the file
        """
        self.state += 1
        lines       = ''
        if self.state <= self.total+1:
            for i in xrange(self.state):
                lines = '%s%s' % (lines, self.fp.readline())
        else:
            return -1
        self.fp.seek(0)

        return lines

>>> test = MyFile('text.txt')
>>> test.nextline()

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

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