在 Python 中使用 listdir 时出错
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15452099/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Error while using listdir in Python
提问by Sakura
I'm trying to get the list of files in a particular directory and count the number of files in the directory. I always get the following error:
我正在尝试获取特定目录中的文件列表并计算目录中的文件数。我总是收到以下错误:
WindowsError: [Error 3] The system cannot find the path specified: '/client_side/*.*'
My code is:
我的代码是:
print len([name for name in os.listdir('/client_side/') if os.path.isfile(name)])
I followed the code example given here.
我遵循了此处给出的代码示例。
I am running the Python script on Pyscripter and the directory /client_side/ do exists. My python code is in the root folder and has a sub-folder called "client_side". Can someone help me out on this?
我在 Pyscripter 上运行 Python 脚本并且目录 /client_side/ 确实存在。我的 python 代码位于根文件夹中,并且有一个名为“client_side”的子文件夹。有人可以帮我解决这个问题吗?
采纳答案by Sakura
I decided to change the code into:
我决定将代码更改为:
def numOfFiles(path):
return len(next(os.walk(path))[2])
and use the following the call the code:
并使用以下调用代码:
print numOfFiles("client_side")
Many thanks to everyone who told me how to pass the windows directory correctly in Python and to nrao91 in herefor providing the function code.
非常感谢所有告诉我如何在 Python 中正确传递 windows 目录的人,并感谢这里的nrao91提供函数代码。
EDIT: Thank you eryksun for correcting my code!
编辑:感谢 eryksun 更正我的代码!
回答by GodMan
As I can see a WindowsError, Just wondering if this has something to do with the '/' in windows ! Ideally, on windows, you should have something like os.path.join('C:','client_side')
正如我所看到的WindowsError,只是想知道这是否与 Windows 中的“/”有关!理想情况下,在 Windows 上,你应该有类似的东西os.path.join('C:','client_side')
回答by sissi_luaty
You want:
你要:
print len([name for name in os.listdir('./client_side/') if os.path.isfile(name)])
with a "." before "/client_side/".
用“.” 在“/client_side/”之前。
The dot means the current path where you are working (i.e. from where you are calling your code), so "./client_side/" represents the path you want, which is specified relatively to your current directory.
点表示您正在工作的当前路径(即从您调用代码的位置),因此“./client_side/”代表您想要的路径,它是相对于您的当前目录指定的。
If you write only "/client_side/", in unix, the program would look for a folder in the root of the system, instead of the folder that you want.
如果你只写“/client_side/”,在 unix 中,程序会在系统的根目录中寻找一个文件夹,而不是你想要的文件夹。
回答by schlenk
Two things:
两件事情:
- os.listdir() does not do a glob pattern matching, use the globmodule for that
- probably you do not have a directory called '/client_side/*.*', but maybe one without the .in the name
- os.listdir() 不进行 glob 模式匹配,为此使用glob模块
- 可能您没有名为“/client_side/*.*”的目录,但可能没有. 在名字里
The syntax you used works fine, if the directory you look for exists, but there is no directory called '/client_side/.'.
如果您要查找的目录存在,但没有名为 '/client_side/ 的目录,则您使用的语法可以正常工作。'。
In addition, be careful if using Python 2.x and os.listdir, as the results on windows are different when you use u'/client_side/' and just '/client_side'.
此外,使用 Python 2.x 和 os.listdir 时要小心,因为当您使用 u'/client_side/' 和仅使用 '/client_side' 时,Windows 上的结果是不同的。
回答by nymk
This error occurs when you use os.listdiron a pathwhich does not refer to an existing path.
For example:
当您使用时出现此错误os.listdir一个在路径不指向现有的路径。
例如:
>>> os.listdir('Some directory does not exist')
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
WindowsError: [Error 3] : 'Some directory does not exist/*.*'
If you want to use os.listdir, you need to either guarantee the existence of the path that you would use, or use os.path.existsto check the existence first.
如果您想使用os.listdir,您需要保证您将使用的路径的存在,或者os.path.exists首先用于检查是否存在。
if os.path.exists('/client_side/'):
do something
else:
do something
Suppose your current working directory is c:\foobar, os.listdir('/client_side/')is equivalent to os.listdir('c:/client_side'), while os.listdir('client_side/')is equivalent to os.listdir('c:/foobar/client_side'). If your client_side directory is not in the root, such error will occur when using os.listdir.
假设您当前的工作目录是c:\foobar,os.listdir('/client_side/')相当于os.listdir('c:/client_side'),而os.listdir('client_side/')相当于os.listdir('c:/foobar/client_side')。如果你的client_side目录不在根目录下,使用os.listdir.
For your 0 ouput problem, let us recall os.listdir(path)
对于您的 0 输出问题,让我们回忆一下 os.listdir(path)
Return a list containing the namesof the entries in the directory given by path. The list is in arbitrary order. It does not include the special entries '.' and '..' even if they are present in the directory.
返回一个包含路径给定目录中条目名称的列表。该列表的顺序是任意的。它不包括特殊条目“.” 和 '..' 即使它们存在于目录中。
and os.path.isfile(path).
Return True if pathis an existing regular file. This follows symbolic links, so both islink() and isfile() can be true for the same path.
如果路径是现有的常规文件,则返回 True 。这遵循符号链接,因此 islink() 和 isfile() 对于同一路径都可以为真。
listdirreturns neither the absolute paths nor relative paths, but a list of the name of your files, while isfilerequires path. Therefore, all of those names would yield False.
listdir既不返回绝对路径也不返回相对路径,而是返回文件名称的列表,而isfile需要路径。因此,所有这些名称都会产生False.
To obtain the path, we can either use os.path.join, concat two strings directly.
要获取路径,我们可以使用os.path.join, 直接连接两个字符串。
print ([name for name in os.listdir(path)
if os.path.isfile(os.path.join(path, name))])
Or
或者
print ([name for name in os.listdir('client_side/')
if os.path.isfile('client_side/' + name)])
回答by user2174865
You can do just
你可以只做
os.listdir('client_side')
without slashes.
没有斜线。
回答by Joe
If you just want to see all the files in the directory where your script is located, you can use os.path.dirname(sys.argv[0]). This will give the path of the directory where your script is.
如果只想查看脚本所在目录中的所有文件,可以使用os.path.dirname(sys.argv[0]). 这将给出脚本所在目录的路径。
Then, with fnmatchfunction you can obtain the list of files in that directory with a name and/or extension specified in the filenamevariable.
然后,fnmatch您可以使用函数获取该目录中具有filename变量中指定的名称和/或扩展名的文件列表。
import os,sys
from fnmatch import fnmatch
directory = os.path.dirname(sys.argv[0]) #this determines the directory
file_name= "*" #if you want the python files only, change "*" to "*.py"
for path, subdirs, files in os.walk(directory):
for name in files:
if fnmatch(name, file_name):
print (os.path.join(path, name))
I hope this helps.
我希望这有帮助。
回答by DaveSawyer
Checking for existence is subject to a race. Better to handle the error (beg forgiveness instead of ask permission). Plus, in Python 3 you can suppress errors. Use suppress from contextlib:
检查存在性受制于比赛。更好地处理错误(请求宽恕而不是请求许可)。另外,在 Python 3 中,您可以抑制错误。使用来自 contextlib 的抑制:
with suppress(FileNotFoundError):
for name in os.listdir('foo'):
print(name)

