Python:选择目录中的第一个文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31613409/
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
Python: Select the first file in a directory
提问by Lerenn
I'm trying to process some files in a directory without knowing their name, and one by one.
So I've used os.listdir(path)
to list files.
我试图在不知道名称的情况下处理目录中的一些文件,并且一一处理。所以我习惯于os.listdir(path)
列出文件。
So I have to list files at each call of my function. The problem is when there is a lot of files (like 2000), it takes a loooooong time to list each file and I just want the first one.
所以我必须在每次调用我的函数时列出文件。问题是当有很多文件(比如 2000)时,列出每个文件需要很长时间,而我只想要第一个。
Is there any solution to get the first name without listing each files ?
有没有办法在不列出每个文件的情况下获得名字?
Thank you :)
谢谢 :)
采纳答案by helloV
If your goal is to process each file name, use os.walk() generator:
如果您的目标是处理每个文件名,请使用 os.walk() 生成器:
Help on function walk in module os:
walk(top, topdown=True, onerror=None, followlinks=False)
Directory tree generator.
回答by Michael Neylon
os.listdir(path)[0]
It would be faster than 'listing' (printing?) each filename, but it still has to load all of the filenames into memory. Also, which file is the first file, do you only want whichever one comes first or is there a specific one you want, because that is different.
这比“列出”(打印?)每个文件名要快,但它仍然必须将所有文件名加载到内存中。另外,哪个文件是第一个文件,您只想要第一个文件还是您想要的特定文件,因为那是不同的。
回答by Nikhil Shinday
It seems like you're trying to process the files en masse, and you'll be iterating through all the files at some point. Instead of having calling the method every time that you enter your function, why not have a global parameter so that you only load the list once? So, for example, instead of:
似乎您正在尝试整体处理文件,并且您将在某个时候遍历所有文件。与其每次输入函数时都调用该方法,为什么不用全局参数以便只加载列表一次?因此,例如,而不是:
import os
def foo(path):
os.listdir(path)[0]
you have:
你有:
import os
fnames = os.listdir(path)
def foo(path):
fnames[0]