如何使用python获取特定目录中的文件列表,而忽略符号链接?

如何使用python获取特定目录中的文件列表,而忽略符号链接?,python,Python,我需要通过创建文件名列表来处理目录中的文件名。 但我的结果列表也包含符号链接的条目。如何使用python获得特定目录中的纯文件名 我尝试过:os.walk、os.listdir、os.path.isfile 但所有这些都包括指向列表的'filename~'类型的符号链接:( glob.glob将路径添加到我不需要的列表中 我需要在这样的代码中使用它: files=os.listdir(folder) for f in files: dosomething(like find s

我需要通过创建文件名列表来处理目录中的文件名。 但我的结果列表也包含符号链接的条目。如何使用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)
有什么帮助吗?或者请告诉我正确的答案。谢谢


编辑:波浪号在末尾

您可以使用
os.path.islink(您的文件)
检查您的文件是否有符号链接,并将其排除

类似这样的东西对我很有用:

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

要获取目录中的常规文件,请执行以下操作:

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), '*[!~]')

基于
而不是file.startswith(“~”)
如果您需要支持OS X别名,请参阅此处:@kuzzooroo am using linuxThank@padraiccningham。如果不是f.endswith(“~”),我使用了“files=[f for f for f in OS.listdir(folder)”]“。它似乎起作用了。很抱歉,波浪符号在末尾,并编辑了我的问题。如果是在末尾,请使用
而不是file.endswith(“~”)
我尝试了files=[f for f in os.listdir(folder)if not os.path.islink(os.path.join(folder,f)),但文件列表仍然包含符号链接:(@Kaur,我已经加入了一个在笔记本电脑上可用的示例。谢谢。我尝试了你之前建议的“fnmatch”。似乎不起作用。@Kaur:这就是我删除它的原因。我添加了
fnmatch
有效的解决方案。是的,这个“fnmatch”有效。之前的是“*~”。非常感谢!