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

2024-05-16 09:21:01 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我从一个名为archive的文件运行此代码,在archive中有更多的文件夹,在每个文件夹中都有一个或多个文本文件。我想列出一个包含这些文件夹路径的列表。但是出现以下错误。

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

我现在有一个python脚本,我把这段代码写在与archive相同的文件夹中,它会触发这个错误。我该怎么做才能停止此错误并获取所有文件路径。

我很不擅长使用操作系统,而且我不经常使用它,所以如果这是一个微不足道的问题,我道歉。

编辑

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'

Tags: pathin路径文件夹foros错误items
1条回答
网友
1楼 · 发布于 2024-05-16 09:21:01

你一定在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.

编辑:

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

我在我的“D:”驱动器中创建了存档文件夹。在archive文件夹下,我创建了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']

相关问题 更多 >