如何在Python中讀取資料夾中的多個文字檔案?(Tkinter)
Python能夠處理檔案、物件並建立不同的應用程式。我們可以使用Python的擴充套件和包來構建和開發功能齊全的應用程式。
假設您想控制系統中的檔案;那麼Python提供了一個OS模組,它具有系統啟用功能,允許您與作業系統中的檔案進行互動。
讓我們看看如何使用Python中的OS模組讀取資料夾中的多個文字檔案。
在您的筆記本中匯入OS模組。
定義系統中文字檔案所在的路徑。
建立一個檔案列表並迭代以查詢它們是否都具有正確的副檔名。
使用模組中定義的函式讀取檔案。
示例
# Import the required libraries
import os
# Define the location of the directory
path =r"C:/Users/Sairam/Documents/"
# Change the directory
os.chdir(path)
def read_files(file_path):
with open(file_path, 'r') as file:
print(file.read())
# Iterate over all the files in the directory
for file in os.listdir():
if file.endswith('.txt'):
# Create the filepath of particular file
file_path =f"{path}/{file}"
read_files(file_path)輸出
Sample 1 ======== Welcome to Tutorialspoint. You are browsing the best resource for Online Education. Sample 2 ======== A distributed ledger is a type of data structure which resides across multiple computer devices, generally spread across locations or regions. Distributed ledger technology (DLT) includes blockchain technologies and smart contracts. While distributed ledgers existed prior to Bitcoin, the Bitcoin blockchain marks the convergence of a host of technologies, including timestamping of transactions, Peer-to-Peer (P2P) networks, cryptography, and shared computational power, along with a new consensus algorithm.
我們在指定位置有兩個文字檔案,程式讀取了這兩個檔案的內容並在控制檯中顯示了文字。
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP