我尝试打印目录的所有文件名称:
import os
dir = '/etc'
def fr(dir):
filelist = os.listdir(dir)
for i in filelist:
fullfile = os.path.join(dir, i)
if not os.path.isdir(fullfile):
print(fullfile)
else:
fr(fullfile)
fr(dir)
但结果就像吼叫:
.....
/etc/man.conf
/etc/manpaths
/etc/master.passwd
/etc/master.passwd~orig
/etc/my.cnf
/etc/my.cnf.bak
/etc/nanorc
/etc/networks
/etc/networks~orig
/etc/newsyslog.conf
/etc/nfs.conf
/etc/nfs.conf~orig
/etc/notify.conf
.....
你知道,在/etc/ssh/
下,有很多文件,但它没有打印,只打印第一级文件。第二级文件和更深的文件没有打印。
有人可以帮我打印所有文件名吗?
答案 0 :(得分:0)
你可以使用import os
来实现它可能是这样的:
import os
for dirname, dirnames, filenames in os.walk('C:/'): #provide which folder you need to list
# print path to all subdirectories first.
for subdirname in dirnames:
print(os.path.join(dirname, subdirname))
# print path to all filenames.
for filename in filenames:
print(os.path.join(dirname, filename))
结果如下:
======== RESTART: C:\dev\sandbox\test.py ========
C:/$Recycle.Bin
C:/boot
C:/dev
C:/Documents and Settings
C:/_SMSTaskSequence
C:/appConfig.json
C:/BOOTSECT.BAK
C:/dev.7z
C:/for
......
C:/test.txt
and etc.: