os.walk问题 [英] os.walk question
问题描述
如何使用os.walk制作顶级目录中的文件列表
。
我需要从中说选择随机文件清单。
谢谢。
- 张贴于 news://freenews.netfront.net - 对 ne ** @ netfront.net -
7月24日,11:52 * am,Lanny < la ... @ freshells.chwrote:
如何制作顶级目录中的文件列表
使用os .walk。
我需要从列表中选择一个随机文件。
所以你只需要一个目录中的文件?
尝试:_,_,files = os。 walk(''/ top / folder / here'')。next()
单下划线是一个表示我们不在乎的约定
那些结果。
。需要.next()来逐步执行os.walk,这将在你指定的路径上开始
。 br />
希望这会有所帮助。
- alex23
Lanny写道:
如何使用os.walk制作顶级目录中的文件列表
。
我需要从列表中选择一个随机文件。
如果你想要一个目录中的文件列表,请使用listdir,而不是walk:
>> import os,random
random.choice(os.listdir(" /&\")))b $ b
''python25''
< / F>
7月23日,5:22 * pm,Fredrik Lundh< fred ... @ pythonware.comwrote:
if you want一个目录中的文件列表,使用listdir,而不是走:
* * *>> import os,随机
* * *> ;> random.choice(os.listdir(" /"))
* * *''python25''
这也包括文件夹,但这不是OP
要求的。
>>导入操作系统,随机
root =" /"
random.choice(如果操作系统在[os.listdir(root)中为f,则为f) .path.isfile(os.path.join(root,f))])
''initrd.img''
与os.walk相比,它看起来很笨拙。
How would one make a list of the files in the top directory
using os.walk.
I need to pick a random file from said list.
Thanks.
-- Posted on news://freenews.netfront.net - Complaints to ne**@netfront.net --
On Jul 24, 11:52*am, "Lanny" <la...@freshells.chwrote:How would one make a list of the files in the top directory
using os.walk.
I need to pick a random file from said list.So you -only- want the files from one directory?
Try: _, _, files = os.walk(''/top/folder/here'').next()
The single underscore is a convention to indicate we don''t care about
those results.
The .next() is needed to step through os.walk once, which will start
at the path you specify.
Hope this helps.
- alex23
Lanny wrote:
How would one make a list of the files in the top directory
using os.walk.
I need to pick a random file from said list.if you want a list of files from a single directory, use listdir, not walk:
>>import os, random
random.choice(os.listdir("/"))
''python25''
</F>
On Jul 23, 5:22*pm, Fredrik Lundh <fred...@pythonware.comwrote:if you want a list of files from a single directory, use listdir, not walk:
* * * >>import os, random
* * * >>random.choice(os.listdir("/"))
* * * ''python25''This will include folders as well, though, which isn''t what the OP
asked for.
>>import os, random
root = "/"
random.choice([f for f in os.listdir(root) if os.path.isfile(os.path.join(root, f))])
''initrd.img''
It just seems clunky compared to os.walk :)
这篇关于os.walk问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!