首页 > 解决方案 > 使用 Python,能够从另一个目录迭代文件但无法读取内容

问题描述

我需要从当前目录遍历另一个目录中的所有 .txt 文件并读取内容。

我能够迭代 thw 文件名,但是当尝试读取内容时,当文件中有数据时,输出是空白的。

标签: pythonloopsdirectory

解决方案


为此,这里有一个如何迭代当前目录中的每个文本文件的示例

# 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'

推荐阅读