[英]Moving into a directory without knowing its name
Im a noob to python and I am trying to complete this simple task. 我是python的菜鸟,我正在尝试完成此简单的任务。 I want to access multiple directories one by one that are all located inside one directory.
我要一一访问多个目录,这些目录都位于一个目录中。 I do not have the names of the multiple directories.
我没有多个目录的名称。 I need to enter into the directory, combine some files, move back out of that directory, then into the next directory, combine some files, move back out of it, and so on........ I need to make sure I dont access the same directory more than once.
我需要进入目录,合并一些文件,移出该目录,然后进入下一个目录,合并一些文件,移出该目录,依此类推........我需要确保我不会多次访问同一目录。
I looked around and tried various commands and nothing yet. 我环顾四周,尝试了各种命令,但什么也没有。
try using something like the following piece of code.: 尝试使用类似以下代码的代码:
import os, fnmatch
def find_files(directory, pattern):
for root, dirs, files in os.walk(directory):
for basename in files:
if fnmatch.fnmatch(basename, pattern):
filename = os.path.join(root, basename)
yield filename
use it something like this: 用这样的东西:
for filename in find_files('/home/', '*.html')
# do something
Sometimes I find glob to be useful: 有时我发现glob很有用:
from glob import glob
import os
nodes = glob('/tmp/*/*')
for node in nodes:
try:
print 'now in directory {}'.format(os.path.dirname(node))
with open(node, 'r') as f:
# Do something with f...
print len(f.read())
except IOError: # Because node may be a directory, which we cannot 'open'
continue
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.