python - 使用 Python,能够从另一个目录迭代文件但无法读取内容
问题描述
我需要从当前目录遍历另一个目录中的所有 .txt 文件并读取内容。
我能够迭代 thw 文件名,但是当尝试读取内容时,当文件中有数据时,输出是空白的。
解决方案
为此,这里有一个如何迭代当前目录中的每个文本文件的示例
# Import the module OS
import os
# Choose Current Directory
directory = os.getcwd()
# Iterate over every file in the directory
for filename in os.listdir(directory):
# get the full path by concatenating the file name with the directory
path = directory + "\\" + filename
# Check if this file is a text file
if path.endswith(".txt"):
# Open the text files in the path
text_file = open(path, 'r')
# Read and print the contents of these files (Including the Python Script)
print(text_file.read())
您可以使用所需的任何目录更改当前目录。
如果您对其他目录有疑问,请尝试在 URL 中使用双反斜杠,如下所示
directory = 'C:\\Users\\USER\\Desktop\\Text Files'
推荐阅读
- php - wordpress 中的 Bootstrap Navwalker 父链接问题
- python - Python多处理退出条件间歇性错误
- javascript - 在具有多个循环的函数中使用 var?
- excel - 如何检查空值或行具有全零值或具有多个值
- java - 如果我在 Spring boot 中使用多个方法映射,如何仅从 swagger ui 文档中隐藏一个映射
- reactjs - 两个组件之间的路由
- json - jq - select objects and print null for missing
- python-3.x - 使用 tf_agents.environments.TFPyEnvironment 将 Python RL 环境转换为 TF 环境时会发生哪些变化?
- sql - 如何计算 2 列
- python - keras Tensorflow中InputLayer的输入形状是什么?