2016-11-19 8 views
-2

Python(ver 3.5.2)でTkinterでアプリケーションを作成していますが、次の問題があります。Python ver 3.5.2でファイルから(1つの文字列から別の複数行に)読み込む方法

ファイルからデータを読みたい(ある文字列から別の文字列に複数の行に)。 「開始」ストリングはユーザーの選択で、終了ストリングが決定され、「=」です。私はこれまで何をやったか

は次のとおりです。

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

例:

ユーザーエントリ: "土"

ファイル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

関連する問題