有没有办法在Python中返回当前目录中所有子目录的列表?
我知道你可以用文件做到这一点,但我需要获取目录列表.
我想在文件夹中打开一系列子文件夹,找到一些文本文件并打印一些文本文件行.我用这个:
configfiles = glob.glob('C:/Users/sam/Desktop/file1/*.txt')
Run Code Online (Sandbox Code Playgroud)
但是这也无法访问子文件夹.有谁知道如何使用相同的命令来访问子文件夹?
我想知道什么是pythonic函数:
我想删除wa路径前的所有内容.
p = path.split('/')
counter = 0
while True:
if p[counter] == 'wa':
break
counter += 1
path = '/'+'/'.join(p[counter:])
Run Code Online (Sandbox Code Playgroud)
例如,我想'/book/html/wa/foo/bar/'成为'/wa/foo/bar/'.
我有一个root-ish目录,其中包含多个子目录,所有子目录都包含文件名data.txt.我想要做的是编写一个接收"root"目录的脚本,然后读取所有子目录并读取子目录中的每个"data.txt",然后将每个data.txt文件中的内容写入输出文件.
这是我的代码片段:
import os
import sys
rootdir = sys.argv[1]
with open('output.txt','w') as fout:
for root, subFolders, files in os.walk(rootdir):
for file in files:
if (file == 'data.txt'):
#print file
with open(file,'r') as fin:
for lines in fin:
dosomething()
Run Code Online (Sandbox Code Playgroud)
我的dosomething()部分 - 如果我只为一个文件运行该部分,我已经测试并确认它可以正常工作.我还确认,如果我告诉它打印文件(注释掉的行),脚本会输出'data.txt'.
现在,如果我运行它,Python会给我这个错误:
File "recursive.py", line 11, in <module>
with open(file,'r') as fin:
IOError: [Errno 2] No such file or directory: 'data.txt'
Run Code Online (Sandbox Code Playgroud)
我不确定为什么它找不到它 - 毕竟,如果我取消注释'print file'行,它会打印出data.txt.我做错了什么?
我在大型硬盘上乱码python中的文件查找.我一直在看os.walk和glob.我经常使用os.walk,因为我发现它更整洁,似乎更快(对于通常的大小目录).
有没有人对他们有任何经验,可以说哪个更有效率?正如我所说,glob似乎更慢,但你可以使用通配符等,就像walk一样,你必须过滤结果.以下是查找核心转储的示例.
core = re.compile(r"core\.\d*")
for root, dirs, files in os.walk("/path/to/dir/")
for file in files:
if core.search(file):
path = os.path.join(root,file)
print "Deleting: " + path
os.remove(path)
Run Code Online (Sandbox Code Playgroud)
要么
for file in iglob("/path/to/dir/core.*")
print "Deleting: " + file
os.remove(file)
Run Code Online (Sandbox Code Playgroud) 如何使用pathlib以递归方式迭代给定目录的所有子目录?
p = Path('docs')
for child in p.iterdir(): child
Run Code Online (Sandbox Code Playgroud)
似乎只是迭代给定目录的直接子节点.
我知道这是可能的os.walk()或glob,但我想使用pathlib因为我喜欢使用路径对象.