[英]python readline() returns multiple lines
我想我為自己制造了一個問題。
我有兩個函數和一個全局文件描述符(文件對象)
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()時,它返回第一行。
如果再次調用它將返回第一行和第二行。
如果再次調用它,則返回第一行,第二行和第三行。 等等等
文件描述符是全局變量會導致這種情況嗎?
完整的未編輯代碼可以在這里找到
感謝所有幫助!
編輯:包括更多的上下文代碼
EDIT2:添加了指向github項目文件的鏈接
解決:問題是:
ui.fileControl.clicked.connect(nextLine)
不會斷開先前的信號。 因此,每次單擊Control()文件時,都會添加“信號和插槽”,以便多次調用newLine()。 並且由於fileController仍被調用,因此文件被重新打開。 所以我看到了上面的行為。 感謝所有的建議!
您可以編寫一個類來封裝此類操作:
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.