如何在Python 3.5.2版中读取文件(从一个字符串到另一个-多行)
我正在用Tkinter在PythonVer3.5.2中创建一个应用程序,我在以下方面遇到了问题 我想将文件中的数据从一个字符串读取到另一个字符串-多行。起始字符串是用户的选择,结束字符串是确定的,即“=” 到目前为止,我所做的是:如何在Python 3.5.2版中读取文件(从一个字符串到另一个-多行),python,file,user-interface,tkinter,Python,File,User Interface,Tkinter,我正在用Tkinter在PythonVer3.5.2中创建一个应用程序,我在以下方面遇到了问题 我想将文件中的数据从一个字符串读取到另一个字符串-多行。起始字符串是用户的选择,结束字符串是确定的,即“=” 到目前为止,我所做的是: #click on button writes data from file: open = Button(self, text="Open", command = self.openTXT, width=20).grid(row=5, column=3,
#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
感谢您的帮助。您可以使用一个标志来指示何时捕获数据-
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不同的名称,以便在阅读代码时理解它。我看不出有问题。您需要帮助解决方案的哪一部分?非常感谢。它解决了我的问题。我还将self.text.insert1.0行更改为self.text.insertEND行,以便它的组织方式与文件中的完全相同。