【问题标题】:python readline() returns multiple linespython readline() 返回多行
【发布时间】:2013-12-04 00:55:58
【问题描述】:

我想我给自己制造了一个问题......

我有两个函数和一个全局文件描述符(文件对象)

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()

调用 nextLine() 时,它返回第一行。
如果再次调用它,它会返回第一行和第二行。
如果再次调用它,它会返回第一行、第二行和第三行。 等等等等。

文件描述符是全局变量会导致这种情况吗?

完整的未编辑代码可以在here找到

感谢所有帮助!

编辑:包含更多上下文代码
EDIT2:添加到 github 项目文件的链接

已解决: 问题是:

ui.fileControl.clicked.connect(nextLine)

不断开前一个信号。所以每次点击文件 Control() 时都会添加一个“信号和插槽”,以便多次调用 newLine()。并且由于仍在调用 fileController,因此正在重新打开文件。所以我看到了上面的行为。谢谢大家的建议!

【问题讨论】:

  • 发布一个示例解释器会话。 (真实的;在交互式解释器中运行代码并复制/粘贴脚本。)
  • 你的函数没有返回任何东西
  • 它实际上对我来说运行良好。应该归咎于调用它的代码。
  • @user2357112 在交互式解释器中运行良好。因此,我将编辑问题以显示围绕此代码的代码。

标签: python readline


【解决方案1】:

你可以写一个类来封装这些操作:

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()

【讨论】:

  • 同意。使用全局变量通常是个坏主意,当它用于跨多个函数执行 I/O 时更糟糕。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-26
相关资源
最近更新 更多