在 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.

更新於:22-Dec-2021

9K+ 瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告