如何用Python忽略符号链接获得特定目录中的文件列表?

2 投票
2 回答
3908 浏览
提问于 2025-04-29 22:02

我需要处理一个文件夹里的文件名,想要创建一个文件名的列表。但是我得到的列表里也包含了符号链接的条目。我该如何用Python获取某个文件夹里纯粹的文件名呢?

我试过了:os.walk, os.listdir, os.path.isfile

但是这些方法都把类型为'filename~'的符号链接也加进列表里了 :(

而且glob.glob会把路径也加到列表里,这个我不需要。

我需要在这样的代码中使用它:

files=os.listdir(folder)    
for f in files:
     dosomething(like find similar file f in other folder)

有没有人能帮帮我?或者请把我引导到正确的答案。谢谢!

编辑:波浪号是在文件名的末尾

暂无标签

2 个回答

1

你可以用 os.path.islink(yourfile) 来检查你的文件是否是一个符号链接,如果是的话就把它排除掉。

像这样的方法对我来说是有效的:

folder = 'absolute_path_of_yourfolder' # without ending /
res = []
for f in os.listdir(folder):
    absolute_f = os.path.join(folder, f)
    if not os.path.islink(absolute_f) and not os.path.isdir(absolute_f):
        res.append(f)

res # will get you the files not symlinked nor directory
...
1

要获取一个文件夹里的普通文件:

import os
from stat import S_ISREG

for filename in os.listdir(folder):
    path = os.path.join(folder, filename)
    try:
        st = os.lstat(path) # get info about the file (don't follow symlinks)
    except EnvironmentError:
        continue # file vanished or permission error
    else:
        if S_ISREG(st.st_mode): # is regular file?
           do_something(filename)

如果你仍然看到 'filename~' 这样的文件名,那就说明它们其实不是符号链接。你可以通过文件名来过滤掉它们:

filenames = [f for f in os.listdir(folder) if not f.endswith('~')]

或者使用 fnmatch 来过滤:

import fnmatch

filenames = fnmatch.filter(os.listdir(folder), '*[!~]')

撰写回答