简体   繁体   English

FileNotFoundError 在 python 中使用 listdir

[英]FileNotFoundError Using listdir in python

so I have a directory with a few subdirectories in it and I am trying to iterate through all the subdirectories I have (each subdirectory has a bunch of files in it that I'm splitting up into smaller files).所以我有一个目录,里面有几个子目录,我正在尝试遍历我拥有的所有子目录(每个子目录中有一堆文件,我将它们分成较小的文件)。 i've been trying to use os.listdir but I keep getting this error FileNotFoundError: [Errno 2] No such file or directory: 'mFAPA'我一直在尝试使用os.listdir但我不断收到此错误 FileNotFoundError: [Errno 2] No such file or directory: 'mFAPA'

This subdirectory definitely exists, so I'm not sure why this keeps happening这个子目录肯定存在,所以我不确定为什么会这样

for dir in os.listdir('../conv_files'):
    for filename in os.listdir(dir):

I was trying to use the for loops to go through each directory and then in each directory go through each file.我试图通过每个目录使用for循环到go,然后通过每个文件在每个目录中使用go。 The error is on the second line of code, once it's in the parent directory it for some reason can't do the for filename in os.listdir(dir) part.错误在代码的第二行,一旦它在父目录中,由于某种原因它不能for filename in os.listdir(dir) Any suggestions?有什么建议么?

You can use os.walk() which traverses into each subdirectory and files inside a given directory.您可以使用 os.walk() 遍历给定目录中的每个子目录和文件。 Refer https://www.geeksforgeeks.org/os-walk-python/ for more details有关更多详细信息,请参阅https://www.geeksforgeeks.org/os-walk-python/

for (root,dirs,files) in os.walk('../conv_files'):
   #add your code here

syntax : os.listdir(path)语法:os.listdir(path)

Parameters : path (optional): path of the directory参数:path(可选):目录的路径

Return Type : This method returns the list of all files and directories in the specified path.返回类型:此方法返回指定路径中所有文件和目录的列表。 The return type of this method is list.该方法的返回类型是列表。

in your first nested loop, it consists of the file names but os.listdir(path) requires path in it.在您的第一个嵌套循环中,它由文件名组成,但 os.listdir(path) 需要路径。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM