如何在 Python 中从文件夹中读取多个文本文件?(Tkinter)
tkinterpythongui-programming更新于 2025/7/12 14:04:17
Python 能够处理文件、对象和创建不同的应用程序。我们可以使用 Python 的扩展和包来构建和开发功能齐全的应用程序。
假设您想控制系统中的文件;然后 Python 提供了一个 OS 模块,它具有系统启用的功能,允许您与操作系统中的文件进行交互。
让我们看看如何使用 Python 中的 OS 模块从文件夹中读取多个文本文件。
将 OS 模块导入到您的笔记本中。
定义文本文件在系统中所在的路径。
创建一个文件列表并进行迭代以查找它们是否都具有正确的扩展名。
使用模块中定义的函数读取文件。
示例
# 导入所需的库
import os
# 定义目录的位置
path =r"C:/Users/Sairam/Documents/"
# 更改目录
os.chdir(path)
def read_files(file_path):
with open(file_path, 'r') as file:
print(file.read())
# 遍历目录中的所有文件
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.
我们在指定位置有两个文本文件,程序读取这两个文件的内容并在控制台上显示文本。
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

