python - 在 python 中导航子目录时找不到 OSError 文件?

标签 python

有一个目录树结构,其中article是主文件夹,d10x是子文件夹

/articles
  /d101
    1.txt 2.txt 3.txt
  /d102
    1.txt 2.txt 3.txt
  /d103
    1.txt 2.txt 3.txt
  /d104
  .....
  .....
  .....
  /d200

我的程序必须转到每个子文件夹并从中读取文本文件。
我的 python 实现出现以下错误
操作系统错误:[Errno 2]没有这样的文件或目录:'d101'
Python代码:

articles = os.listdir("articles")
mo=[]
for yo in articles:
  mo.append(yo)
for index in range(len(mo)):
  yo=os.listdir(mo[index])
  for article in yo:
     print 'Reading articles/' + article

操作系统错误:[Errno 2] 没有这样的文件或目录:“d101”

最佳答案

您正在尝试读取 d101 而不是 articles/d101。将您的 listdir() 调用更改为:

os.listdir(os.path.join("articles", mo[index]))

关于python - 在 python 中导航子目录时找不到 OSError 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35627512/

相关文章:

python - 一行代码来保存 if 语句的值(value)?

python - 将字符串解析为字典

python - 附加到列表时未调用 Setattr 方法

python - Ctypes:分配 double** ,将其传递给 C,然后在 Python 中使用

python - import matplotlib.pyplot 给出 ImportError : dlopen(…) Library not loaded libpng15. 15.dylib

python - matplotlib 中的多进程绘图

python - 为什么找不到子字符串时 Python 会抛出错误?

python - Py3 : Can't open file/snapshot/serverless/lib/plugins/aws/invokeLocal/invoke. py:没有那个文件或目录

Python:xPath 在 ElementTree 中不可用

python - 为什么迭代元素数组乘法在 numpy 中变慢?