列出unix目录/子目录中的所有文件

时间:2014-02-28 02:23:06

标签: python unix python-2.7 file-io stat

我创建了以下python脚本来列出导演/子目录中存在的所有文件及其大小

代码A

files = glob.glob("%s/*.*"%os.getcwd())

sorted_file = sorted(files, key=os.path.getsize)

for path, dirs, files in os.walk(os.getcwd()):
    for d in dirs:
        for f in glob.iglob(os.path.join(path, d, '*.*')):
            print f ,os.path.getsize(f)

当它运行目录时,我收到以下错误:

Traceback (most recent call last):
  File "Test.py", line 27, in <module>
    print f ,os.path.getsize(f)
  File "/usr/lib/python2.6/genericpath.py", line 49, in getsize
    return os.stat(filename).st_size
OSError: [Errno 2] No such file or directory: '/My/Folder/Perlx.x'

奇怪的是,当我转到unix框中的/My/Folder/并执行ls -l时,我可以看到Perlx.x,其结果是Symbolic Link

代码B

for path, subdirs, files in os.walk(os.getcwd()):
    for name in files:
        f = os.path.join(path, name)
        print f,os.path.getsize(f)

错误:

/My/Folder/BEA
Traceback (most recent call last):
  File "Test.py", line 19, in <module>
    print f,os.path.getsize(f)
  File "/usr/lib/python2.6/genericpath.py", line 49, in getsize
    return os.stat(filename).st_size
OSError: [Errno 2] No such file or directory: '/My/Folder/BEA'

在这两种情况下,BEA和Perlx.x都是Symbolic Links,它们会在指定的文件夹中退出。我如何摆脱这个错误?

1 个答案:

答案 0 :(得分:0)

为了摆脱这个错误,我提出了一个额外的条件来检查文件是否是链接。

   for path, subdirs, files in os.walk(choicedir):
        for name in files:
            f = os.path.join(path, name)
            if not os.path.islink(f):
                modified = os.path.getmtime(f)
                size = float(os.path.getsize(f))