在 Python 中要求用户选择一个文件夹来读取文件
如果您想知道 Python 应用程序中的对话框如何工作,那么您可能会最终在 Tkinter 中听到filedialog 模块。filedialog 模块包含许多内置函数,可以用来显示各种类型的对话框,用于处理系统中的文件。
在大多数情况下,我们使用filedialog.askopenfilename() 函数来要求用户浏览系统中的文件并打开它。脚本根据文件类型的选择进行编程,以执行写入或读取操作。
打开文件后,您可以使用open(file, 'mode') 函数以任何模式打开并执行操作。为了演示这一点,让我们举个例子,我们将创建一个应用程序,该应用程序将要求用户打开一个文本文件。一旦选择了文件并打开它,我们就可以使用操作的“读取”模式读取此文件。
示例
# Import the library from tkinter import * from tkinter import filedialog # Create an instance of window win=Tk() # Set the geometry of the window win.geometry("700x300") # Create a label Label(win, text="Click the button to open a dialog", font='Arial 16 bold').pack(pady=15) # Function to open a file in the system def open_file(): filepath = filedialog.askopenfilename(title="Open a Text File", filetypes=(("text files","*.txt"), ("all files","*.*"))) file = open(filepath,'r') print(file.read()) file.close() # Create a button to trigger the dialog button = Button(win, text="Open", command=open_file) button.pack() win.mainloop()
输出
运行以上代码将显示一个带有一个按钮的窗口,用于打开一个对话框。
选择并打开一个文本文件,控制台将显示文件的全部内容。
Centralized Database Vs Blockchain A blockchain can be both permissionless (like Bitcoin or Ethereum) or permissioned (like the different Hyperledger blockchain frameworks). A permissionless blockchain is also known as a public blockchain, because anyone can join the network. A permissioned blockchain, or private blockchain, requires pre-verification of the participating parties within the network, and these parties are usually known to each other. Types of Blockchains The choice between permissionless versus permissioned blockchains should be driven by the particular application at hand (or use case). Most enterprise use cases involve extensive vetting before parties agree to do business with each other. An example where a number of businesses exchange information is supply chain management. The supply chain management is an ideal use case for permissioned blockchains. You would only want trusted parties participating in the network. Each participant that is involved in the supply chain would require permissions to execute transactions on the blockchain. These transactions would allow other companies to understand where in the supply chain a particular item is.
广告