尝试读取目录时出现目录错误

问题描述 投票:0回答:1

我已在 .txt 文件的其他目录上多次使用此代码,但这次它在 .xml 文件的新目录上给我一个目录错误。有什么想法可能是什么问题吗?

还有一个第二个问题:我从其他地方得到了这段代码,但我不能 100% 确定第二个代码块在做什么。我确实知道它会打印出一个文件名列表,这对我来说是一个有用的检查,但是谁能告诉我它与文件名变量的命名还有什么关系?


base_dir = 'DIRECTORY NAME'
all_docs = []
docs = os.listdir(base_dir)

for doc in docs:
filename = os.fsdecode(doc
if not doc.startswith('.'):
print(os.path.join(base_dir, filename))

for doc in docs:
if not doc.startswith('.'):
#this next line is the line I get an Errno 21 Is a directory 
with open(base_dir, "r", encoding='utf-8) as file:
text = file.read()
all_docs.append(text_LATA)

len(all_docs)

我尝试将 docs = os.listdir(base_dir) 行更改为 docs = os.walk(base_dir) 每个此处提出的另一个问题,但这导致我收到类型错误(预期为 str、bytes 或 os.PathLike 对象,而不是元组)在下一个代码块上。

python gensim word2vec
1个回答
-1
投票

再次查看代码片段后,我想提供更清晰、更准确的解释。此更新的代码使用 pathlib 模块来探索指定目录,从以 .xml、.txt 或 .rst 结尾的文件中提取内容。提取的数据(包括文件内容和文件名)存储在字典列表中,并打印相关的检索消息。

from pathlib import Path

# Convert directory_path to a Path object
directory_path = Path("<DIRECTORY>")

fetched_filesnames = []
# Check if the specified directory exists
if directory_path.is_dir():
    # Iterate over items in the directory
    for item in directory_path.iterdir():
        # Check if the item is a file and has a valid extension
        if item.is_file() and any(item.name.endswith(extension) for extension in ['.xml', '.txt', '.rst']):
            # Open the file and read its content
            with item.open('r', encoding='utf-8', errors='ignore') as file:
                fetched_filesnames.append({"filename": item.name, "content": file.read()})
                # Print fetched content for each file
                print(f"Fetched the content of {item.name}")
© www.soinside.com 2019 - 2024. All rights reserved.