簡體   English   中英

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

[英]Listing all files in a unix directory/sub-directory

我創建了以下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 我如何擺脫這個錯誤?

為了消除錯誤,我加入了一個額外的條件來檢查文件是否為鏈接。

   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))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM