2016-11-19 75 views
-2

我使用Tkinter在Python(ver 3.5.2)中创建了一个应用程序,并且遇到了以下问题。如何在Python版本3.5.2中从文件中读取(从一个字符串到另一个多行)

我想从文件中读取数据(从一个字符串到另一个字符串 - 多行)。 “起始”字符串是用户选择的,并且结束字符串被确定并且是'='。

什么我迄今所做的是:

#click on button writes data from file: 

    open = Button(self, text="Open", command = self.openTXT, width=20).grid(row=5, column=3, pady=5, padx = 10, sticky=W) 

#user enters the starting string in file 

     self.entry = Entry(self, width=30).grid(sticky = W, pady=7, padx=5, column=4, row=2) 

#i want to display data from file in this Text field 

self.text = Text(self).grid(column=4, row=4,pady=8, padx=5, columnspan=2, rowspan=6,sticky=E+W+S+N) 

#this function finds the starting string and writes down line in which getInfo is found. How do I add the end string (the end string in my case is '=') and read multiple lines and not just one, like it is right now 
def openTXT(self): 
     getInfo = self.entry.get() 
     f = open('mojDnevnik.txt', encoding='utf-8') 
     for line in f.readlines(): 
      if getInfo in line: 
       self.text.insert(1.0, line) 

例子:

用户条目: “SAT”

文件mojDnevnik.txt:

Friday Nov 18 2016 

Testing 

========================================== 

Sat Nov 19 2016 

Testing reading from file 

========================================== 

输出应该是:

Sat Nov 19 2016 

Testing reading from file 

感谢您的帮助。

+1

我没有看到问题。您需要哪些解决方案帮助? –

回答

0

你可以使用一个标志到信号时捕获数据 -

def openTXT(self): 
    getInfo = self.entry.get() 
    f = open('mojDnevnik.txt', encoding='utf-8') 
    flag = False 
    for line in f.readlines(): 
     if getInfo in line: 
      self.text.insert(1.0, line) 
      flag = True 
     elif flag and not line.startswith('='): 
      self.text.insert(1.0, line) 
     elif line.startswith('='): 
      flag = False 

当然,你可能需要使用不同的名称flag所以代码有意义当你阅读。

+0

非常感谢。它解决了我的问题。我还将'self.text.insert(1.0,line)'更改为'self.text.insert(END,line)',以便它的组织方式与文件中的完全相同。 – Nika

相关问题