Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

ขอให้ผู้ใช้เลือกโฟลเดอร์เพื่ออ่านไฟล์ใน Python

หากคุณเคยสงสัยว่าไดอะล็อกบ็อกซ์ทำงานอย่างไรในแอปพลิเคชัน Python คุณน่าจะได้ยินเกี่ยวกับโมดูล filedialog ใน Tkinter โมดูล filedialog มีฟังก์ชันในตัวหลายตัวที่สามารถใช้แสดงไดอะล็อกประเภทต่างๆ สำหรับจัดการไฟล์ในระบบ

ในส่วนใหญ่ เราใช้ฟังก์ชัน filedialog.askopenfilename() เพื่อขอให้ผู้ใช้เรียกดูและเปิดไฟล์จากระบบ ตามการเลือกประเภทไฟล์ สคริปต์จะถูกเขียนโปรแกรมให้ดำเนินการอ่านหรือเขียน

เมื่อเปิดไฟล์แล้ว คุณสามารถใช้ฟังก์ชัน open(file, 'mode') เพื่อเปิดและดำเนินการในโหมดใดๆ เพื่อสาธิต มาดูตัวอย่างที่เราจะสร้างแอปพลิเคชันขอให้ผู้ใช้เปิดไฟล์ข้อความ เมื่อเลือกและเปิดไฟล์แล้ว เราสามารถอ่านไฟล์นี้ได้โดยใช้โหมด "read"

ตัวอย่าง

# นำเข้าไลบรารี
from tkinter import *
from tkinter import filedialog

# สร้างอินสแตนซ์หน้าต่าง
win = Tk()

# กำหนดเรขาคณิตหน้าต่าง
win.geometry("700x300")

# สร้างป้ายกำกับ
Label(win, text="Click the button to open a dialog", font='Arial 16 bold').pack(pady=15)

# ฟังก์ชันเปิดไฟล์ในระบบ
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()

# สร้างปุ่มเพื่อทริกเกอร์ไดอะล็อก
button = Button(win, text="Open", command=open_file)
button.pack()

win.mainloop()

ผลลัพธ์

การรันโค้ดด้านบนจะแสดงหน้าต่างพร้อมปุ่มเปิดไดอะล็อก

ขอให้ผู้ใช้เลือกโฟลเดอร์เพื่ออ่านไฟล์ใน Python

เลือกและเปิดไฟล์ข้อความ และคอนโซลจะแสดงเนื้อหาทั้งหมดของไฟล์

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.