Python :[错误3]系统找不到指定的路径:

Python :[Error 3] The system cannot find the path specified:

import os
Current_Directory = os.getcwd() # Should be ...\archive
CORPUS_PATHS = sorted([os.path.join("archive", directories) for directories in os.listdir(Current_Directory)])
filenames = []
for items in CORPUS_PATHS:
    filenames.append(sorted([os.path.join(CORPUS_PATHS, fn) for fn in os.listdir(items)]))

print filenames

我运行从一个名为存档的文件中获取此代码,存档中有更多文件夹,每个文件夹中都有一个或多个文本文件。我想制作一个列表,其中包含每个文件夹的路径。但是出现以下错误。

[Error 3] The system cannot find the path specified:

我目前有 python 脚本,我在其中将这段代码写在与存档相同的文件夹中,它会触发此错误。我应该怎么做才能停止此错误并获取所有文件路径。

我很不擅长使用 os,而且我不经常使用它,所以如果这是一个微不足道的问题,我深表歉意。

编辑

import os
startpath = "archive"
corpus_path = sorted([os.path.join("archive/", directories) for directories in os.listdir(startpath)])

filenames = []
for items in corpus_path:
    print items
    path = [os.path.join(corpus_path, fn) for fn in os.listdir(items)]
    print path

所以我取得了一些进展,现在我的语料库路径本质上是一个列表,其中包含所有所需文件夹的路径。现在我想做的就是获取这些文件夹中文本文件的所有路径,但我仍然 运行 遇到问题,我不知道如何解决

之类的错误
File "C:\Users\David\Anaconda\lib\ntpath.py", line 65, in join
result_drive, result_path = splitdrive(path)

File "C:\Users\David\Anaconda\lib\ntpath.py", line 116, in splitdrive
normp = p.replace(altsep, sep)

AttributeError: 'list' object has no attribute 'replace'

您必须在 windows 机器上。错误是因为 os.listdir()。 os.listdir() 没有得到正确的路径。

在第 3 行中,您正在执行 os.path.join("archive", 目录)。 您应该加入包括驱动器(C: 或 D:)的完整路径,例如“c:/archive/foo: 或 linux "home/root/archive/foo"

阅读 - Python os.path.join on Windows

os.path.join Usage -

On Windows, the drive letter is not reset when an absolute path component (e.g., r'\foo') is encountered. If a component contains a drive letter, all previous components are thrown away and the drive letter is reset. Note that since there is a current directory for each drive, os.path.join("c:", "foo") represents a path relative to the current directory on drive C: (c:foo), not c:\foo.

编辑:

您在第 6 行将列表 corpus_path 传递给 [os.path.join][2]。这会导致错误!将 corpus_path 替换为 items.

我在 'D:' 驱动器中创建了存档文件夹。在存档文件夹下,我创建了 3 个文件夹 foo1、foo2 和 foo3。每个文件夹包含 1 或 2 个文本文件。然后我在修改后测试了你的代码。代码工作正常。 这是代码:

import os
startpath = "d:archive"
corpus_path = sorted([os.path.join("d:", "archive", directories) for directories in os.listdir(startpath)])

filenames = []
for items in corpus_path:
    print items
    path = [os.path.join(items, fn) for fn in os.listdir(items)]
    print path

输出:

d:archive\foo1
['d:archive\foo1\foo1.txt.txt', 'd:archive\foo1\foo11.txt']
d:archive\foo2
['d:archive\foo2\foo2.txt.txt']
d:archive\foo3
['d:archive\foo3\foo3.txt.txt']